1

Is there a way to convert this, so that it checks for balance based on height? (Assuming this is what the problem is.)

size :: Tree a -> Int
size (Leaf n)    = 1
size (Node x z) = size x + size z + 1

isBalanced :: Tree a -> Bool
isBalanced (Leaf _) = True
isBalanced (Node l r) = 
    let diff = abs (size l - size r) in
    diff <= 1 && isBalanced l && isBalanced r

For example:

isBalanced (Node (Node (Leaf 1)(Leaf 3)) (Leaf 2)) )  = True (Currently returns False)
isBalanced (Node (Node (Leaf 1)(Node (Leaf 1)(Leaf 3))) (Leaf 2))) = False
Zast
  • 492
  • 2
  • 7
  • 22

1 Answers1

3

It seems that size counts the total number of nodes. If you want to compute the (maximum) height instead, you want something like this:

height :: Tree x -> Int
height (Leaf _) = 1
height (Node x y) = 1 + (height x `max` height y)

If you just replace size with height, the isBalanced code should work as before.

Whether this fixes your problem remains to be seen, of course...

MathematicalOrchid
  • 61,854
  • 19
  • 123
  • 220