2016-12-05 1 views
0

Quelqu'un peut-il indiquer ce qui ne va pas avec mon code? D'après ce que j'ai observé, la racine de retour ne fonctionne pas correctement comme il se doit.Java: Profondeur récursive de la première traversée

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' et' root.mother' ... c'est une structure arborescente extrêmement bizarre. –

Répondre

0

Modifier votre code comme ci-dessous:

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

Cela vous aidera à comprendre récursion, et vous pouvez l'écrire d'une manière beaucoup mieux. Informez-moi si vous avez encore des problèmes.

0

Vous effectuez un appel récursif qui n'utilise pas la valeur renvoyée. Essayez ceci:

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