[英]Why can't I get the height of a BST in one statement (Java)
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:这是被接受的 Java 代码:
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.但是,当我去提交第二个语句时,它给了我一个运行时错误和 NPE。 Is the
if (root == null){return -1};
是
if (root == null){return -1};
a base case that the second statement doesn't implicitly have?第二条语句不隐含的基本情况?
Yes, when root
is null then root.left
is called that's why you are getting NPE.是的,当
root
是 null 时, root.left
被调用,这就是你得到 NPE 的原因。
And recursive function needs a base case which not called the recursive function again.并且递归 function 需要一个基本案例,它不会再次调用递归 function。 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.在这里,当
root
是null
时,这意味着您在root.left
或root.right
上调用getHeight()
,其中root
是树的叶子,这是基本情况。
@Eklavya has the right answer here, but since you're learning and I love recursion a couple good rules of thumb to add. @Eklavya 在这里有正确的答案,但是由于您正在学习并且我喜欢递归,因此可以添加一些好的经验法则。
root.left()
not root.left
).root.left()
而不是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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.