2016-12-05 18 views
0

コードで何が間違っていると指摘できますか?私が観察したところから、戻り値のルートは正常に動作しません。以下のようにJava:再帰的な深さの最初の走査

private Node find(String name, Node root) 
    { 
    if (root != null) 
    { 
     if (root.name.equals(name)){ 
     System.out.println(root.name); 
     return root; 
     } 
     find(name, root.father); 
     find(name, root.mother); 
     System.out.println(root.name + "This"); 
    } 
    return null; 
    } 

    public void addParents(String ego, String father, String mother) 
    { 
    Node temp = find(ego); 
    if (temp == null) 
     throw new IllegalArgumentException("No such name."); 
    temp.father = new Node(father, null, null); 
    temp.mother = new Node(mother, null, null); 
    System.out.println(temp.name + " | " + temp.father.name + " | " + temp.mother.name); 
    } 
+0

'root.father'と' root.mother' ...これは非常に奇妙なツリー構造です。 –

答えて

0

編集してコード:

Node n = find(name, root.father); 
if (n!=null && n.name.equals(name)) 
{ 
    return n; 
} 
n = find(name, root.mother); 
if (n!=null && n.name.equals(name)) 
{ 
    return n; 
} 

これは、あなたが再帰を理解するのに役立ちます、そしてあなたがより良い方法でそれを書くことができます。

まだ問題がある場合は教えてください。

0

戻り値を使用しない再帰呼び出しを行っています。これを試してください:

public Node find(String name, Node root){ 

     Node findNode = null; 

     if (root != null){ 
      if (root.name.equals(name)){ 
       System.out.println(root.name); 
       return root; 
      } 

      findNode = find(name, root.father); 

      if(findNode!=null){ 
       return findNode; 
      } 

      findNode = find(name, root.mother); 

      if(findNode!=null){ 
       return findNode; 
      } 
     }    
     return null;    
     } 
関連する問題