我试图在非二叉树中搜索节点,而不实际将节点传递给搜索方法。
每个节点都有一个name
变量。 findChild()
方法采用一个名称,并在调用它的树中搜索以查找具有该名称的节点。
为了进行递归搜索,我在子节点上调用 findChild()
,而不是将子节点传递给 findChild()
方法。打印语句显示该方法通过树向下,但当堆栈展开时,result
变量被设置为 null,因此该方法始终返回 null。我明白它为什么这样做,但我不明白如何展开这种类型的递归。如有任何帮助,我们将不胜感激!
我的findChild()
方法:
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;
}
最佳答案
下面的小改动会有帮助吗?您的 else 条件永远不会分配值。
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;
}
关于java - 通过树递归搜索而不传递对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40156565/