java二进制搜索树中的空指针异常

时间:2016-04-20 18:24:58

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

我一直得到一个空指针异常。任何帮助,为什么这将是伟大的。我相信问题存在于我的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;
    }

}

1 个答案:

答案 0 :(得分:0)

当您以递归方式将父/母传递给方法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);
}