0

我不斷收到空指針異常。任何幫助,爲什麼這將是偉大的。我相信問題存在於我的find(String name,Node root)方法中。如何解決這個問題的任何幫助都會很好。謝謝Java二叉搜索樹中的空指針異常

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; 
    } 

} 
+0

什麼是您的具體問題?除非您更具體,否則您的問題可能會被視爲「不是真正的問題」。我們不是爲了幫助您爲您編寫代碼。 – GreenGiant

+0

你的空指針異常來自哪一行?你能發佈你的錯誤堆棧跟蹤嗎? – GreenGiant

+0

有一個問題埋在那裏。它已被多次回答。但是,'私人節點發現(字符串,節點)返回null;' –

回答

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); 
} 
+0

好吧,這是有道理的。謝謝你的提示。 – Doom3030