Search code examples
javarecursiontreestack-unwinding

Recursive search through tree without passing object


I'm trying to search for a node in a non-binary tree without actually passing a node to the search method.

Each node has a name variable. The findChild() method takes a name, and searches through the tree it was called on to find the node with that name.

To do the recursive search, I call findChild() on the child node rather than passing the child node to the findChild() method. Print statements show me that the method gets down through the tree, but the result variable gets set to null as the stack is unwinded, so the method always returns null. I understand why it's doing this, but I don't understand how to unwind this type of recursion. Any help is appreciated!

My findChild() method:

public FileNode findChild(String name) {
    FileNode result = null;
        for (FileNode child : this.getChildren()) {
            if (child.getName() == name) {
                return child;
            } else {
                child.findChild(name);
            }
        }
    return result;
}

Solution

  • Will the following small change help? Your else condition is never assigning a value.

    public FileNode findChild(String name) {
        FileNode result = null;
            for (FileNode child : this.getChildren()) {
                if (child.getName() == name) {
                    result = child;
                    break;
                } else {
                    result = child.findChild(name);
                    if (result != null)
                        break;
                }
            }
        return result;
    }