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);
  }
1
  • root.father and root.mother... that is one extremely weird tree structure. Commented Dec 5, 2016 at 6:32

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.