【问题标题】:null pointer exception in a java binary search tree [duplicate]java二叉搜索树中的空指针异常[重复]
【发布时间】:2016-04-20 18:24:57
【问题描述】:

我不断收到空指针异常。关于为什么会这样的任何帮助都会很棒。我相信问题出在我的 find(String name, Node root) 方法中。任何有关如何解决此问题的帮助都会很棒。谢谢

public class FamilyTree{

    private Node root;

    private class Node
    {
        private String name;
        private Node father;
        private Node mother;
        private Node(String name, Node father, Node mother)
        {
            this.name = name;
            this.father = father;
            this.mother = mother;
        }
    }

    public FamilyTree(String ego)
    {
        this.root = new Node(ego, null, null);
    }

    private Node find(String name)
    {
        return find(name, root);
    }

    private Node find(String name, Node root)
    {
        if( name != null) {
            if (root.name.equals(name)) {
                return root;
            } else {
                find(name, root.father);
                find(name, root.mother);
            }
        }
        return null;
    }

    public void addParents(String ego, String father, String mother)
    {
        if (find(ego) == null)
        {
            throw new IllegalArgumentException();
        }
        else
        {
            find(ego).father = new Node(father,null, null);
            find(ego).mother = new Node(mother, null, null);
        }
    }

    public boolean isDescendant(String ego, String ancestor)
    {
        if(find(ego) == null ||find(ancestor) == null )
        {
            return false;
        }
        else
        {
            return isDescendant(find(ego), find(ancestor));
        }
    }

    public boolean isDescendant(Node root, Node ancestor)
    {
        if( ancestor != null)
        {
            if (root.equals(ancestor))
            {
                return true;
            }
        }

        return false;
    }

}

【问题讨论】:

  • 您的具体问题是什么?除非您更具体,否则您的问题可能会以“不是一个真正的问题”而结束。我们不是来帮你编写代码的。
  • 你的空指针异常来自哪一行?你能发布你的错误堆栈跟踪吗?
  • 里面有一个问题。已经回答过很多次了。但是,private Node find(String, Node) return null;

标签: java nullpointerexception binary-search-tree tree-traversal


【解决方案1】:

当您递归地将父/母传递给方法find 时,您不会检查这些引用是否为空。你也忽略递归调用的返回值:

private Node find(String name, Node root) {
    if (name == null || root == null) {
        return null;
    }
    if (root.name.equals(name)) {
        return root;
    }
    String parentName = find(name, root.father);
    if (parentName != null) {
        return parentName;
    }
    return find(name, root.mother);
}

【讨论】:

  • 好吧,这是有道理的。谢谢你的提示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 2016-04-28
相关资源
最近更新 更多