在java中实现树的DFS

在java中实现树的DFS,java,function,tree,depth-first-search,Java,Function,Tree,Depth First Search,请在下面找到树类定义 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 T

请在下面找到树类定义

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;
  }
}
公共类树{
私人T型头;
private List leafs=new ArrayList();
私有树父级=null;
私有映射locate=newhashmap();
公树(T头){
这个头=头;
定位。放(头,这个);
}
公共void addLeaf(T根,T叶){
if(locate.containsKey(根)){
locate.get(根)、addLeaf(叶);
}否则{
addLeaf(根),addLeaf(叶);
}
}
公共树添加叶(T叶){
树t=新树(叶);
添加(t);
t、 父=此;
t、 locate=this.locate;
定位。放置(叶,t);
返回t;
}
}
树类对象在另一个类中创建,节点以简单的方式添加(使用addLeaf(node)函数)。这个过程可以构建树。是否有人能够根据上述类定义建议在构建的树上实现DFS函数

多谢各位


这就是我尝试过的。是的,它给了我毫无意义的结果

protected void DFS() {
    for(Tree<T> child : leafs) {
        DFS();
        System.out.println(child);
    }
}
protectedvoid DFS(){
用于(树子:树叶){
DFS();
系统输出打印项次(子项);
}
}
代码来自


protectedvoid DFS(){
用于(树子:树叶){
child.DFS();
System.out.println(child.head);
}
}

决心

你很接近了。打印应该是节点的值,递归应该在子节点上。

?所以不是一个“给我代码”的网站。你试过什么?
leafs
应该是
leaves
——你肯定不是指:)@JimGarrison这是我第一次实现树。我试图以自上而下的方式理解这个过程,因为我找不到足够支持自下而上学习过程的教程。
protected void DFS() {
  for(Tree<T> child : leafs) {
      child.DFS();
      System.out.println(child.head);
  }
}