我的任务是从字符串 targetName
给出的通用树中查找并返回特定节点。看看下面我的实现:
public GeneralTreeNode findNode(String targetName) {
if (this.name.equals(targetName)) {
return this;
} else {
for (GeneralTreeNode child : this.children) {
return child.findNode(targetName);
}
}
// no node containing the string could be found
return null;
}
唯一的问题是,当事实上节点确实存在时,这似乎经常错误地返回 null。就好像最后一行 return null
太贪婪了。
在这个节点上设置几个断点并观察它,它似乎只会下降到最低深度,直到节点没有子节点,在这种情况下它只是返回 null。
任何人都可以提供有关如何改进此问题的建议吗?
最佳答案
将代码更改为:
public GeneralTreeNode findNode(String targetName) {
if (this.name.equals(targetName)) {
return this;
} else {
for (GeneralTreeNode child : this.children) {
GeneralTreeNode childResult = child.findNode(targetName);
if (childResult != null) {
return childResult; // only return if you really found something
}
}
}
// no node containing the string could be found
return null;
}
您只想在子搜索确实找到某些内容时返回结果。
关于Java:我的一般树遍历实现有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32878568/