【发布时间】:2017-03-04 09:03:35
【问题描述】:
我有一棵树。这棵树中的所有节点都有一些真/假值、一个元素和父/子指针。此树中的一个元素的真/假值设置为真。我想找到从根到这个唯一节点的路径(元素序列)。所以如果我的树看起来像这样:
A
/ \
B C
/ \
D E
/ \
F G
/ \
H I
而特殊节点是 H,我的算法将返回字符串“ACEGH”。我已经使用 DFS 实现了这一点。但是,我当前的算法是从不正确的路径中添加节点的元素。所以我当前的算法会返回:“ABDCEFGHI”。
private String dfs(Node node, String path) {
if(node.special){
return key;
}
for(Node n: node.children){
if(n != null){
path = path + n.element;
dfs(n, path);
}
}
return null;
}
【问题讨论】:
标签: java algorithm data-structures tree depth-first-search