0

我正在尝试编写一个方法,该方法返回给定节点的父节点。

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;

}

但是,我收到 NullPointerExceptions,当其中一个或两个子节点都是空节点并且 equals 尝试将该值与空值进行比较时。我该如何继续解决这个问题?我还是 Java 新手。

4

2 回答 2

1

在对它们调用方法之前,您确实需要检查它们是否不为空。在这种情况下,您调用current.getLeft().getValue()但左孩子可能为空。如果它为空,您将获得 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;

}
于 2013-05-29T22:03:37.143 回答
0

对于对象变量,当值是null没有对象可以提供您将调用的方法时。

您将对象变量的值null与:

if (obj == null) {
    ... do whatever ...
}

在许多情况下,您可以将对象与 null 进行比较,如下所示:

if (obj.equals(null)) ...

或者

String s = null;

if (obj.equals(s)) ... this works
if (s.equals(obj)) ... this doesn't work

笔记

在您的代码中,如果您要搜索的节点是根节点,它将永远找不到它。

同样,您检查所有子项以查看它们是否匹配,然后通过将值与父项进行比较来决定哪些子项可以匹配。也许您应该重新排序,以便测试当前节点

如果它为空,则搜索以失败告终。如果匹配,则返回您在上次迭代中保存的父级。如果不匹配,则根据值和循环获取正确的孩子——右或左。

这样做的好处是,只有在知道节点不为空时才能获取节点的值。

T eValue = e.getValue();

BinarySearchTreeNode<T> prev = null;
BinarySearchTreeNode<T> current = this.root;
while (current != null) {
    int compare = eValue.compareTo(current.getValue());
    if (compare == 0) {
        return prev;
    }

    prev = current; // save the parent in case it matches
    if (compare < 0) {
        current = current.getLeft();
    } else {
        current = current.getRight();
    }
}
于 2013-05-29T22:05:33.340 回答