0

I have a findNode method that finds a target string in a treenode. The issue I am having is that my recursive method only seems to go down one branch of the tree and not cover the hole tree like I thought it should. If you require anymore code please ask.

public GeneralTreeNode findNode(String targetName) {
  // name is the current name of the node
  if(targetName.equals(this.name)) return this;
  // children is a HashSet of all the nodes children
  for(GeneralTreeNode child : children) return child.findNode(targetName);

  // no node containing the string could be found
  return null; 
}
1
  • Thanks for all responses! Commented Sep 25, 2014 at 8:20

3 Answers 3

1

You're returning in your loop, hence why it stops. Instead of always returning, only return if you find something.

for(GeneralTreeNode child : children) {
   GeneralTreeNode result = child.findNode(targetName);
   if (result != null) {
        return result;
   }

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

1 Comment

Thanks! knew I wasn't far off. Makes a lot more sense.
0

Change to such chode:

public GeneralTreeNode findNode(String targetName) {

  // name is the current name of the node
  if(targetName.equals(this.name)) return this;

  // children is a HashSet of all the nodes children
  for(GeneralTreeNode child : children) { 
     GeneralTreeNode result = child.findNode(targetName);
     if (result != null) return result;
  }

  // no node containing the string could be found
  return null; 
}

This should work as you want...

2 Comments

This will not compile, you have the return in the result assignment.
True, this is typo mistake, i have edited. thanks @Evan
0

In this line

for(GeneralTreeNode child : children) return child.findNode(targetName);

you directly return the result from the first child. So each subsequent child will never be consulted. As this first child also returns the result from its first child, you observe that your method only considers one branch.

The solution is to analyze the result of each child:

for(GeneralTreeNode child : children) {
    GeneralTreeNode result = child.findNode(targetName);
    if (result != null) return result;
}

Now it only returns the result, if the node was really found. If not, the loop continues.

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.