Reputation: 80
I was learning about binary search trees, and a practice problem involved recursively finding the height of the tree.
This is the Java code that was accepted:
public static int getHeight(Node root){
if (root == null)
return -1;
else {
int leftHeight = getHeight(root.left);
int rightHeight = getHeight(root.right);
if (leftHeight > rightHeight)
return leftHeight + 1;
else
return rightHeight + 1;
}
}
And this was the code (given as pseudocode in the tutorial) I tried at first and thought would work:
public static int getHeight(Node root){
return 1 + Math.max(getHeight(root.left), getHeight(root.right));
}
However when I went to submit the second statement, it gave me a runtime error and NPEs. Is the if (root == null){return -1};
a base case that the second statement doesn't implicitly have?
Upvotes: 1
Views: 54
Reputation: 18430
Yes, when root
is null then root.left
is called that's why you are getting NPE.
And recursive function needs a base case which not called the recursive function again. Here, when root
is null
that means you are calling getHeight()
on root.left
or root.right
where root
is leaves of the tree that is the base case.
Upvotes: 1
Reputation: 1670
@Eklavya has the right answer here, but since you're learning and I love recursion a couple good rules of thumb to add.
root.left()
not root.left
). It's a bit of pain now, but it will save you thousands of wasted hours if it's a habit you stay in.Upvotes: 0