Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

minimum height in tree

I'm trying to optimize the code:

data Tree = Empty | Node Integer Tree Tree
minHeight Empty = -1
minHeight (Node _ Empty Empty) = 0
minHeight (Node _ l     r    ) = (min (minHeight l) (minHeight r)) + 1

My goal is to not calculate the branches whose depth will be higher than the already known one.

like image 938
Лилия Сапурина Avatar asked Oct 07 '15 09:10

Лилия Сапурина


People also ask

What is the minimum height of a tree?

If you have N elements, the minimum height of a binary tree will be log2(N)+1.

How do you find the maximum and minimum height of a tree?

Calculating minimum and maximum height from the number of nodes: If there are n nodes in a binary search tree, maximum height of the binary search tree is n-1 and minimum height is ceil(log2(n+1))-1.

What is the minimum height of a binary tree?

What is the minimum height of a full binary tree? Full Binary Tree A Binary Tree is a full binary tree if every node has 0 or 2 children. So minimum height of a full binary tree can be 0.

Can a tree have height 0?

Show activity on this post. According to Wikipedia, The height of a tree is the length of the path from the root to the deepest node in the tree. A (rooted) tree with only one node (the root) has a height of zero (or one).


2 Answers

You can use Peano Nats instead of Integers and let laziness do the job:

data Nat = S Nat | Z deriving (Eq)

instance Ord Nat where
    min (S n) (S m) = S (min n m)
    min  _     _    = Z

instance Enum Nat where
    fromEnum  Z    = 0
    fromEnum (S n) = fromEnum n + 1

data Tree = Empty | Node Integer Tree Tree

minHeight  Empty        = Z
minHeight (Node _  l r) = S (min (minHeight l) (minHeight r))

tree = Node 0 (Node 1 tree Empty) tree

main = print $ fromEnum $ minHeight tree -- 2
like image 125
user3237465 Avatar answered Oct 12 '22 23:10

user3237465


Here's a solution, which doesn't calculate the branches, whose depth will be higher then the already known one:

data Tree = Empty | Node Integer Tree Tree

minHeight :: Tree -> Int
minHeight =
  loop Nothing 0
  where
    loop defaultDepth depth tree =
      case defaultDepth of
        Just x | x <= depth ->
          x
        _ ->
          case tree of
            Empty -> depth
            Node _ left right ->
              loop (Just (loop defaultDepth (succ depth) left)) (succ depth) right
like image 25
Nikita Volkov Avatar answered Oct 12 '22 23:10

Nikita Volkov