0

Can someone point out what is wrong with my code? From what I observed, return root doesn't work properly as it should.

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);
  }
Danh
  • 5,916
  • 7
  • 30
  • 45
Shane Ong
  • 11
  • 1

2 Answers2

0

Edit your code as below:

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

This will help you understand recursion, and then you can write it in a much better way.

Let me know if you still have issues.

CompSciFly
  • 144
  • 1
  • 15
Azodious
  • 13,752
  • 1
  • 36
  • 71
0

You are making a recursive call that don't use the returned value. Try this:

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