BinarySearchTree - isBalanced()方法获取NullPointerException - Java

时间:2015-04-20 07:20:08

标签: java nullpointerexception binary-search-tree

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

实验室问题:"考虑一种二元搜索树的方法,该方法决定树是否高度平衡。"

当我做实验时,不知何故我在Test输出中得到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

1 个答案:

答案 0 :(得分:1)

您的计划中左右儿童可能是null,因此在isBalanced(BinaryNode<T> tree)中您应首先判断tree != null,否则tree.getLeftChild();可能会抛出NullPointerException。