2017-08-05 98 views
1

我有以下列方式定義的節點非二進制樹:遞歸的樹搜索在Java中

public class TreeNode{ 
private String label; 
private TreeNode[] children; 

public TreeNode(String label){ 
    this.label = label; 
    children = new TreeNode[9] 
} 

所以每個節點都有一個標籤和大小9數組,它持有其9名兒童。 現在在我的樹類中,我想定義一個find方法,它將查找具有特定標籤的節點。這是我能想出什麼:

public TreeNode find(String label, TreeNode node) { 
    TreeNode result = null; 
    if (node.getLabel().equals(label)) { 
     return node; 
    } else { 
     if (node.hasChildren()){ 
      for (int i = 0; i< node.getChildren().length; i++){ 
       if (node.getChildren()[i].getLabel().equals(label)) { 
        result = node.getChildren()[i]; 
        break; 
       else 
        return find(label, node.getChildren()[i]; 
      } 
    return result; 
} 

而與此問題是,它只是一個更深層次每次不通過「節點」我提供的方法的兄弟姐妹看。

我確定解決方案很簡單,但我似乎無法抓住它。

有一個similar question here,我認爲他們的問題也是類似的,但我似乎無法將提供的解決方案轉換爲我的應用程序。

我錯過了什麼?感謝您的幫助!

回答

2

for循環內不應使用return而不檢查遞歸調用的返回值。此外,無條件地將遞歸調用應用於循環中的所有項目。

for (int i = 0; i < node.getChildren().length; i++){ 
    result = find(label, node.getChildren()[i]; 
    if(result != null) { 
     return result; 
    } 
} 
+0

謝謝。那樣做了。你推薦任何好的資源來學習遞歸嗎? – doddy

+0

@doddy啊,很高興聽到。那麼,我總是覺得遞歸比迭代更容易理解(在大多數情況下)。我純粹通過實驗和對樹和列表的常見遞歸操作的研究來學習。網上有很多來源,所以就是其中之一。如果您感興趣,請查看樹遍歷和操作。 –

+0

@cᴏʟᴅsᴘᴇᴇᴅ最簡單的一個是:「瞭解遞歸,首先必須瞭解遞歸」 – xenteros