java - 每个节点有多个 child 的树的搜索方法

标签 java algorithm recursion data-structures tree

我创建了以下方法来在未排序的树中搜索某个 ParentReference Id,其中每个节点都可以有任意数量的子节点。如果给定的 parentRef 与节点的 parentRef 匹配,则应返回该节点。

public static <T>Node<T> search(Node<T> node, int parentRef) {
    if(node.getParentRef() == parentRef){
        return node;
    }
    if(node.getChildren()!= null){
        for(int i = 0; i < node.getChildren().size(); i++){
            if(node.getChildren().get(i).parentRef == parentRef){
                return node;
            }
            else {
                search(node.getChildren().get(i), parentRef);
            }
        }
    }
    return null;
}

但是,它不起作用,总是返回 null 但我不知道为什么。谁能解释我做错了什么?

最佳答案

else分支中,你递归调用了search,但是没有返回它的值,所以它丢失了。您应该检查它是否不是 null,如果是,则返回它:

else {
    Node<T> result = search(node.getChildren().get(i), parentRef);
    if (result != null) {
        return result;
    }
}

关于java - 每个节点有多个 child 的树的搜索方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48934809/

相关文章:

java - 如何设置 jlabel 的固定大小?

algorithm - 反转 CRC32

javascript - 为什么递归结束返回未定义

java - 有没有一段时间你不会使用递归?

python - 尝试模块化 python 代码但出现递归错误 : maximum recursion depth

java - 减少条件跟踪/记录调用的开销

java - JavaFX 中的绑定(bind)标签 textProperty

java - 字段需要类型为 ... 的 bean,但无法找到

algorithm - 广播信道的最优重传算法

algorithm - Dijkstra 算法中边缘的松弛