I'm trying to figure out a way to calculate the height of the tree using the fact that each nodes knows about its balance. This complexity must be in O(logn)
Here's what I've got so far.
if(!node)
return 0
if(node.balance > 0)
return height(node.right) + 1
if(node.balance < 0)
return height(node.left) + 1
return max( height(T.left), height(T.right)) + 1
My thought was that if the tree is right heavy, traverse the right side and ignore the left. If the tree is left heavy, ignore the right and keep traversing in there. However, I'm a little confused as to what to do if the tree is balanced. At that point, wouldn't we be forced to run max( height(T.left), height(T.right)) + 1
which would mean that each node in the subtree would be visited, hence making this complexity O(n) either way?