【问题标题】:Search method for tree with multiple children per node每个节点有多个孩子的树的搜索方法
【发布时间】:2018-08-02 17:45:34
【问题描述】:

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

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,但我不知道为什么。谁能解释我做错了什么?

【问题讨论】:

  • @Bax 是的。
  • [help-me]“不起作用”还不足以继续下去。请准确解释发生和/或不发生的情况。

标签: java algorithm recursion data-structures tree


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多