2013-03-19 56 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

相关问题