2015-10-01 30 views
1

我的任務是查找並返回由字符串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。

任何人都可以提供有關如何改善此問題的建議嗎?

+1

您需要檢查findNode的返回值,並且只有在* not * null時才返回。 –

回答

2

你的代碼改成這樣:

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; 
} 

你只想從子搜索返回的結果,如果真的發現了什麼。

+0

消除'return null'語句會導致編譯錯誤,不是嗎?這開啓了沒有價值被返回的可能性。 – ReactingToAngularVues

+0

@EchoLogic我對「改變這一部分」非常具體。沒有必要複製沒有改變的代碼,我想。但它也沒有傷害。謝謝蒂姆。 –

+0

這很好,謝謝你的幫助。它看起來不錯。顯然,我在處理遞歸方法時低估了空檢查的重要性。乾杯。 – ReactingToAngularVues

0

如果以這種方式實現,代碼的可讀性將消失。樹遍歷最好在助手類中實現,並將ROOT元素與target_name一起傳遞。

如果你以這種方式返回null,它就像node是null實際上它不是。另一方面,當你使用「doer」或「processor」方法/函數時,它可以返回真實的「我找不到任何東西」。

儘管如此,你的代碼似乎沒問題。我只是重寫它。

static Node search(Node node, String nodeName) { 
    if (node.getName().equals(nodeName)) return node; 

    List<Node> children = node.getChildren(); 
    foreach(Node child : children) { 
     Node resultChild = search(child, nodeName); 
     if (resutlChild != null) return resultChild; 

    } 

    return null; 

} 
+0

'foreach'這不是一個java語法。 – YoungHobbit

+0

這只是編寫在紙上,爲或foreach試圖告訴它正在循環:) –

+0

你應該這樣寫:'for(Node child:children){'。 – YoungHobbit