0
我目前正在学习数据结构,现在我在BinarySearchTree。BinarySearchTree - isBalanced()方法获取NullPointerException - Java
实验问题:“考虑一种二叉搜索树的方法,该树决定树是否高度平衡。”
当我做实验时,不知何故,我在Test输出中得到NullPointerException。我不知道为什么,我在哪里得到一个空。 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
某处,您有一个未初始化的变量,并且您在其上调用方法。检查一下哪个变量,并确保它在调用方法之前被初始化。 – Stultuske
也许你应该学会通过你的代码进行调试。这很容易,你会学习一种艺术,你会在整个职业生涯中使用。 – Aakash