2013-03-19 55 views
0

我正在嘗試編寫返回具有相同標籤的所有節點的路徑的JAVA代碼。Java從根搜索具有相同標籤的所有節點路徑

image specified in link。我應該得到以下O/P爲標籤Ç

A-> B

作爲輸出。

我知道所有可能的標籤。說標籤的範圍可以從A到J.

樹的節點類:

class Node{ 
String label; 
int count; 
List<Node> children; 

public int hashCode() { 
    return label.hashCode(); 
} 

public boolean equals(Object obj) { 
    Node other = (Node)obj; 
    return other.label.equals(label); 
} 
} 

我試圖像

for(each label) 
start from root 
search for all possible label location 
    print path for each label location 

但不能什麼瞭解如何編寫代碼。請幫忙。

回答

0

試試這個:

public List<List<String>> findPaths(String label) { 
    List<List<String>> result = new ArrayList<List<String>>(); 

    if (label.equals(this.label)) { 
     result.add(new ArrayList<String>()); 
    } 

    for (Node child : children) { 
     for (List<String> subResult : child.findPaths(label)) { 
      // add this.label in front 
      List<String> path = new ArrayList<String>(); 
      path.add(this.label); 
      path.addAll(subResult); 
      result.add(path); 
     } 
    } 

    return result; 
} 

每個路徑將被編碼爲StringArrayList一個標籤。我假設每個葉子都有一個空白的孩子列表。如果children == null在葉子中,則需要檢查該問題,否則所有孩子的循環將提高NullPointerException

現在,由於標籤labels的一些列表和一個根節點root

for (String label : labels) { 
    List<List<String>> paths = root.findPaths(label); 
    for (List<String> path : paths) { 
     printPath(path); 
    } 
} 

我相信你可以使自己的功能printPath(List<String> path)打印的實際路徑...

+0

非常感謝。代碼對我來說工作得很好。 我寫簡單printPath功能 私人無效printPath(列表路徑) { 對(INT I = 0; I 2013-03-20 06:08:05

相關問題