【问题标题】:BinarySearchTree - isBalanced() method get NullPointerException - JavaBinarySearchTree - isBalanced() 方法获取 NullPointerException - Java
【发布时间】:2015-04-20 07:20:08
【问题描述】:

我目前正在学习数据结构,现在在 BinarySearchTree。

实验室问题:“考虑一种确定二叉搜索树是否高度平衡的方法。”

当我做实验时,不知何故我在测试输出中得到了 NullPointerException。我不知道为什么以及在哪里得到 Null。 NetBean 说错误来自 BinarySearchTree.isBalanced()

    int leftHeight = left.getHeight();
    int rightHeight = right.getHeight();

    return (tree.getData() == null ) || (isBalanced(left) && isBalanced(right) 
                                       && Math.abs(leftHeight - rightHeight) <= 1);

你们能帮帮我吗?

非常感谢

这是我的 isBalanced() 方法:

public boolean isBalanced(){
    return isBalanced(root);
}
private boolean isBalanced(BinaryNode<T> tree){
    BinaryNode<T> left = tree.getLeftChild();
    BinaryNode<T> right = tree.getRightChild();


    int leftHeight = left.getHeight();
    int rightHeight = right.getHeight();

    return (tree.getData() == null ) || (isBalanced(left) && isBalanced(right) 
                                       && Math.abs(leftHeight - rightHeight) <= 1);
}

这是 BinaryNode 类中的 getHeight() 方法

public int getHeight(){
     return getHeight(this); // call private getHeight
} // end getHeight

private int getHeight(BinaryNode<T> node){
     int height = 0;

     if (node != null)
         height = 1 + Math.max(getHeight(node.left), 
             getHeight(node.right));

     return height;
 } // end getHeight

【问题讨论】:

  • 某处,您有一个未初始化的变量,您正在调用一个方法。检查是哪个变量,并确保在调用方法之前对其进行了初始化。
  • 也许你也应该学会调试你的代码。这很容易,您将学习一门将在整个职业生涯中使用的艺术。

标签: java nullpointerexception binary-search-tree


【解决方案1】:

你的程序中左右孩子可能是null,所以在isBalanced(BinaryNode&lt;T&gt; tree)中你应该先判断tree != null否则tree.getLeftChild();可能会抛出NullPointerException。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多