我正在尝试编写一个方法,它返回给定节点的父节点。
public BinarySearchTreeNode<T> getParent(BinarySearchTreeNode<T> e) {
if (e == null) {
return null;
}
BinarySearchTreeNode<T> current = this.root;
T eValue = e.getValue();
while (current != null) {
if (howManyChildren(current) == 0) {
return null;
} else if (eValue.equals(current.getLeft().getValue())
|| eValue.equals(current.getRight().getValue())) {
return current;
} else if (eValue.compareTo(current.getValue()) < 0) {
current = current.getLeft();
} else {
current = current.getRight();
}
}
return null;
}
但是,当一个或两个子节点都是 null 节点并且 equals 尝试将该值与 null 进行比较时,我会收到 NullPointerException。 我该如何继续解决这个问题?我对 Java 还是个新手。
最佳答案
在调用子级的方法之前,您确实需要检查它们是否不为空。在这种情况下,您调用 current.getLeft().getValue() ,但左子级可能为 null。如果它为 null,您将得到 NullPointerException。
下面是一个示例,在调用该方法之前检查以确保它们不为空。警告,除了 NullPointerException 之外,我没有检查整个代码是否正确。
public BinarySearchTreeNode<T> getParent(BinarySearchTreeNode<T> e) {
if (e == null) {
return null;
}
BinarySearchTreeNode<T> current = this.root;
T eValue = e.getValue();
while (current != null) {
if (howManyChildren(current) == 0) {
return null;
} else if ((current.getLeft()!=null && eValue.equals(current.getLeft().getValue()))
|| (current.getRight()!=null) && eValue.equals(current.getRight().getValue())) {
return current;
} else if (eValue.compareTo(current.getValue()) < 0) {
current = current.getLeft();
} else {
current = current.getRight();
}
}
return null;
}
关于java - 在树中查找父节点时出现 NullPointerExceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16824626/