Recursive search through tree without passing obje

2019-07-21 17:24发布

问题:

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

回答1:

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


回答2:

You're throwing away the result of FileNode#findChild in the else block

Try this

if (child.getName().equals(name)) {
    return child;
} else {
    FileNode childResult = child.findChild(name);
    if (childResult != null) {
        return childResult;
    }
}