1

I have a non-binary Tree with nodes defined in the following way:

public class TreeNode{
private String label;
private TreeNode[] children;

public TreeNode(String label){
     this.label = label;
     children = new TreeNode[9]
}

So each node has a label and an array of size 9 which holds its 9 children. Now in my tree class, I want to define a find method that will find a node with a specific label. This is what I could come up with:

public TreeNode find(String label, TreeNode node) {
    TreeNode result = null;
    if (node.getLabel().equals(label)) {
        return node;
    } else {
        if (node.hasChildren()){
            for (int i = 0; i< node.getChildren().length; i++){
                if (node.getChildren()[i].getLabel().equals(label)) {
                    result = node.getChildren()[i];
                    break;
                else
                    return find(label, node.getChildren()[i];
           }
    return result;
}

And the problem with this is that it just goes a level deeper everytime without looking through the siblings of the "node" I provide to the method.

I'm sure the solution is trivial but I just can't seem to catch it.

There is a similar question here and I think their issue is also similar but I can't seem to translate the provided solution to my application.

What am I missing? Thank you for your help!

cs95
  • 379,657
  • 97
  • 704
  • 746
doddy
  • 579
  • 5
  • 18

1 Answers1

2

You shouldn't use return inside the for loop without checking the returned value of the recursive call. Also, apply the recursive call to all items in the loop unconditionally.

for (int i = 0; i < node.getChildren().length; i++){
    result = find(label, node.getChildren()[i];
    if(result != null) {
        return result;
    }
}
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thank you. That did it. Do you recommend any good resources to learn recursion? – doddy Aug 05 '17 at 06:44
  • @doddy Ah, glad to hear. Well, I always felt recursion was easier to understand than iteration (in most cases). I learned purely through experimentation and the study of common recursive operations with trees and lists. There are a lot of sources online, SO being one of them. Look at tree traversal and operations if you're interested. – cs95 Aug 05 '17 at 06:46
  • 1
    @cᴏʟᴅsᴘᴇᴇᴅ the easiest one is: `to understand recursion, one have to understand recursion first` – xenteros Aug 05 '17 at 06:51