Tree: Height of a Binary Tree

  • + 0 comments

    No, they have counted root node as 0, and empty tree with no node as -1.

    The reason we have to return -1 when (root == null) is that, through recursion we are incrementing count for each node including root node, whereas defination of height is the number of edges connecting root to the farthest leaf, which will clearly be 1 less.

    if (root == null){ return -1; } else{ return 1 + Math.max( getHeight(root.left), getHeight(root.right) ); }