请在下面找到树类定义。
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);
}
}
解决了!
最佳答案
你已经很接近了。打印应该是节点的值,递归应该在子节点上。
关于java - 用java实现树的DFS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9608669/