java - 在树中查找父节点时出现 NullPointerExceptions

标签 java tree parent

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

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/

相关文章:

java - 使用Socket编程发送文件(大)

处理父版本时 Maven3 和 M2eclipse 不匹配?

java - 是否可以使用Java反射或各种技术来检查一个类是否有父类?

java - 创建引用父数组列表的方法

java - 从自定义 ItemReader 访问时无法强制转换 FlatFileItemReader

java - 在输入不匹配错误期间从异常获取 "null"作为消息

java - Spring Data JPA + Hibernate + PostgreSQL

tree - 使用 golang 从表中创建一棵树?

c - 测试树的圆度?

go - 克隆节点 [golang.org/x/net/html] : Stack overflow