【发布时间】:2012-03-07 20:37:43
【问题描述】:
请在下面找到树类定义。
public class Tree<T>{
private T head;
private List<Tree<T>> leafs = new ArrayList<>();
private Tree<T> parent = null;
private Map<T, Tree<T>> locate = new HashMap<>();
public Tree(T head) {
this.head = head;
locate.put(head, this);
}
public void addLeaf(T root, T leaf) {
if (locate.containsKey(root)) {
locate.get(root).addLeaf(leaf);
} else {
addLeaf(root).addLeaf(leaf);
}
}
public Tree<T> addLeaf(T leaf) {
Tree<T> t = new Tree<>(leaf);
leafs.add(t);
t.parent = this;
t.locate = this.locate;
locate.put(leaf, t);
return t;
}
}
Tree 类对象是在另一个类中创建的,并以直接的方式添加节点(使用 addLeaf(node) 函数)。这个过程可以很好地构建树。有人可以在遵循上述类定义的构造树上建议 DFS 函数实现吗?
谢谢。
这是我尝试过的。是的,它给了我毫无意义的结果。
protected void DFS() {
for(Tree<T> child : leafs) {
DFS();
System.out.println(child);
}
}
代码来自link的第三条评论
protected void DFS() {
for(Tree<T> child : leafs) {
child.DFS();
System.out.println(child.head);
}
}
解决了!
【问题讨论】:
-
家庭作业? SO 不是“给我密码”网站。你试过什么?
-
leafs应该是leaves-- 你肯定不是指Maple Leafs :) -
@JimGarrison 这是我第一次实现树。我试图以自上而下的方式理解该过程,因为我找不到足以支持自下而上学习过程的教程。
标签: java function tree depth-first-search