We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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.
Tree: Height of a Binary Tree
You are viewing a single comment's thread. Return to all 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) ); }