我创建了以下方法来在未排序的树中搜索某个 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/