Recursive search through tree without passing object

╄→尐↘猪︶ㄣ 提交于 2019-12-11 01:54:30

问题


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


来源:https://stackoverflow.com/questions/40156565/recursive-search-through-tree-without-passing-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!