我的任務是查找並返回由字符串targetName
給出的一般樹中的特定節點。快來看看下面我的實現:Java:我的一般樹遍歷實現有什麼不正確?
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;
}
唯一的問題是,這往往似乎錯誤地返回空值時,實際上是一個節點確實存在。就好像最後一行return null
太貪婪了。
在這個問題上找到幾個斷點並觀察它,結果表明它似乎只能下到最低深度,直到一個節點沒有子節點,在這種情況下它只是返回null。
任何人都可以提供有關如何改善此問題的建議嗎?
您需要檢查findNode的返回值,並且只有在* not * null時才返回。 –