简体   繁体   English

为什么我不能在一条语句中获得 BST 的高度 (Java)

[英]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.在这里,当rootnull时,这意味着您在root.leftroot.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 在这里有正确的答案,但是由于您正在学习并且我喜欢递归,因此可以添加一些好的经验法则。

  • Always have a termination condition in your code explicitly.在你的代码中总是有一个明确的终止条件。 Making termination implicit may be clever but communicating it and maintaining it are hard隐式终止可能很聪明,但传达和维护它却很困难
  • In Java, always assume a value is null in your method unless you have specifically annotated it otherwise.在 Java 中,始终假定您的方法中的值为 null,除非您另外特别注释了它。 Unprotected child access is always a code smell未受保护的儿童访问始终是一种代码味道
  • Best practice in most languages with explicit privacy (like Java) is not to use members directly but to build an interface and reference methods from the interface ( root.left() not root.left ).大多数具有显式隐私的语言(如 Java)的最佳实践不是直接使用成员,而是构建接口并从接口引用方法( 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM