Calculating the height of a binary tree

Do u know the definition of node's height? I would answer it as the farthest distance to a reachable leaf(so all leaf have height 0)...now try to find the height of every node from bottom to top..that would your algo..


I'll try to explain how this recursive algorithm works:

height(10) = max(height(5), height(30)) + 1

height(30) = max(height(28), height(42)) + 1
height(42) = 0 (no children)
height(28) = 0 (no children)

height(5) =  max(height(4), height(8)) + 1
height(4) = 0 (no children)
height(8) = 0 (no children)

So if you want to calculate height(10), you have to expand the recursion down, and than substitute results backwards.

height(5)  = max(0, 0) + 1
height(30) = max(0, 0) + 1
height(10) = max(1, 1) + 1
height(10) = 2

EDIT:

As noted in comments:
height of binary tree = number of layers - 1
Therefore there should be assumption that height of empty node is equal to -1 i.e:

height(empty) = -1 

or

height(null) = -1 

this way

height(42) = max(height(null), height(null)) + 1
height(42) = max(-1, -1) + 1
height(42) = -1 + 1
height(42) = 0

I have corrected calculation above.


Height of the tree is the length of the path from the root to the deepest node in the tree. Here is the shortest algo to do so

int height(Node root){
   if(root == null )
       return 0;
   return 1+max{height(root.left), height(root.right)};
}