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.
If you have N elements, the minimum height of a binary tree will be log2(N)+1.
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 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.
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).
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
                        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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With