2014-09-25 59 views
0

我有一個findNode方法,它在treenode中查找目標字符串。我遇到的問題是,我的遞歸方法似乎只是沿着樹的一個分支而沒有像我認爲應該覆蓋的洞樹。如果您需要更多代碼,請詢問。遞歸方法沒有翻譯所有的樹節點

public GeneralTreeNode findNode(String targetName) { 
    // name is the current name of the node 
    if(targetName.equals(this.name)) return this; 
    // children is a HashSet of all the nodes children 
    for(GeneralTreeNode child : children) return child.findNode(targetName); 

    // no node containing the string could be found 
    return null; 
} 
+0

感謝您的回覆! – 2014-09-25 08:20:22

回答

1

你在你的循環返回,因此爲什麼它停止。而不是總是返回,只有當你發現一些東西時纔會返回。

for(GeneralTreeNode child : children) { 
    GeneralTreeNode result = child.findNode(targetName); 
    if (result != null) { 
     return result; 
    } 

} 
+0

謝謝!知道我並不遙遠。更有意義。 – 2014-09-25 08:17:47

0

改變這種斥責

public GeneralTreeNode findNode(String targetName) { 

    // name is the current name of the node 
    if(targetName.equals(this.name)) return this; 

    // children is a HashSet of all the nodes children 
    for(GeneralTreeNode child : children) { 
    GeneralTreeNode result = child.findNode(targetName); 
    if (result != null) return result; 
    } 

    // no node containing the string could be found 
    return null; 
} 

這應該工作,只要你想......

+0

這不會編譯,您在結果分配中返回。 – 2014-09-25 08:14:29

+1

的確,這是錯字,我編輯過。謝謝@Evan – 2014-09-25 08:15:43

0

在這一行

for(GeneralTreeNode child : children) return child.findNode(targetName); 

你直接從第一個孩子返回結果。所以每個後來的孩子都不會被諮詢。由於這個第一個孩子也會返回第一個孩子的結果,所以你會發現你的方法只考慮一個分支。

解決方法是分析每個孩子的結果是:

for(GeneralTreeNode child : children) { 
    GeneralTreeNode result = child.findNode(targetName); 
    if (result != null) return result; 
} 

現在它只返回結果,如果節點真的找到。如果沒有,循環繼續。

相關問題