我需要在树中循环以获取所有可能的路径,在我的代码中,我只获得第一个路径的问题!在树状结构中获取所有可能的路径
在该图中,有2条路径吨处理:1-2-3-4-5-6和1-2-3-7-8,但我无法得到两个,我刚刚检索1-2-3-4-5-6!
我的代码:
在主:
for (String key : synset.keySet()) { // looping in a hash of Concept and it's ID
System.out.println("\nConcept: " + key + " " + synset.get(key));
List<Concept> ancts = myOntology.getConceptAncestors(myOntology.getConceptFromConceptID(synset.get(key))); // this function retreives the root of any node.
for (int i = 0; i < ancts.size(); i++) {
System.out.print(ancts.get(i).getConceptId() + " # ");
System.out.print(getChilds(ancts.get(i).getConceptId()) + " -> "); // here, the recursive function is needed to navigate into childs..
}
System.out.println("");
}
建议。功能:
public static String getChilds(String conId)
{
List<Concept> childs = myOntology.getDirectChildren(myOntology.getConceptFromConceptID(conId)); // get all childs of a node
if(childs.size() > 0)
{
for (int i = 0; i < childs.size(); i++) {
System.out.print(childs.size() + " ~ " + childs.get(i).getConceptId() + " -> ");
return getChilds(childs.get(i).getConceptId());
}
}
else
return "NULL";
return "final";
}
问题在于,您只提供我们需要帮助您的部分信息。如果不了解您的树是如何构建的(内部表示),我们不能说您的算法为什么不正确。所以请回过头来,转到帮助中心,并阅读http://stackoverflow.com/help/mcve,除此之外......你知道有很多方法可以遍历树吗? https://en.wikipedia.org/wiki/Tree_traversal – GhostCat
我已经说明了需求清楚.. –
因为'getChilds'方法返回'String'。当一个节点有两个以上的孩子时的问题 – Jerry06