Java 宽度优先的N元树遍历

Java 宽度优先的N元树遍历,java,filesystems,breadth-first-search,n-ary-tree,Java,Filesystems,Breadth First Search,N Ary Tree,我正在编写文件系统层次结构的N元树表示,其中包含一些关于目录/文件的信息。树中的每个节点都包含一个父节点及其子节点(如果有)的列表,并包含在一个单独的树对象中。就我所知,这并不是实现树的最有说服力的方法,但我已经深入到了不值得回头的项目中 public class TreeNode { private FileSystemEntry data; private TreeNode parent; private ArrayList<TreeNode> chil

我正在编写文件系统层次结构的N元树表示,其中包含一些关于目录/文件的信息。树中的每个节点都包含一个父节点及其子节点(如果有)的列表,并包含在一个单独的树对象中。就我所知,这并不是实现树的最有说服力的方法,但我已经深入到了不值得回头的项目中

public class TreeNode {

    private FileSystemEntry data;
    private TreeNode parent;
    private ArrayList<TreeNode> children;
    private boolean directory; //separates files from folders (files have no children) 
我知道在遍历每个节点的子节点(或类似的东西)时,我需要使用队列将每个节点添加到

这里有一个深度优先的递归解决方案,它打印每个文件/目录的名称,仅供参考

public void PrintTreeNames() {

    PrintTreeNames(this.Root);

}

private void PrintTreeNames(TreeNode n) {

    if (!n.isDirectory()) {
        System.out.println(n.getData().getName());
    } else {
        for (int i = 0; i < n.getChildren().size(); i++) {
            PrintTreeNames(n.getChildren().get(i));
        }
        System.out.println(n.getData().getName());
    }

}
public void PrintTreeNames(){
PrintTreeNames(this.Root);
}
私有void PrintTreeNames(TreeNode n){
如果(!n.isDirectory()){
System.out.println(n.getData().getName());
}否则{
for(int i=0;i

我觉得从深度优先到广度优先应该只是一个小小的修改,但我似乎无法控制它

最初只使用根节点创建队列,处理队列直到它为空。要处理节点,请先将其输出,然后将其所有子节点添加到队列中:

public void PrintTreeNames() {

  Queue<TreeNode> queue = new LinkedList<TreeNode>();
  queue.add(this.root);
  TreeNode current;
  while ((current = queue.poll()) != null) {
    PrintTreeNames(current, queue);
  }
}

private void PrintTreeNames(TreeNode n, Queue<TreeNode> queue) {

  System.out.println(n.getData().getName());
  if (n.isDirectory()) {
    for (int i = 0; i < n.getChildren().size(); i++) {
      queue.add(n.getChildren().get(i));
    }
  }
}
public void PrintTreeNames(){
Queue Queue=new LinkedList();
queue.add(this.root);
三极电流;
而((当前=queue.poll())!=null){
PrintTreeNames(当前,队列);
}
}
私有void PrintTreeNames(树节点n,队列){
System.out.println(n.getData().getName());
if(n.isDirectory()){
for(int i=0;i
ahhh当然可以。我曾读到,这两者之间唯一真正的区别是堆栈(DF)和队列(BF),但我感到困惑,因为我的深度优先解决方案没有引用任何堆栈,然后我记得递归调用将自己放在程序堆栈上,以跟踪每个输出:)我将尝试此解决方案,然后返回给youWorks。非常感谢。
public void PrintTreeNames() {

  Queue<TreeNode> queue = new LinkedList<TreeNode>();
  queue.add(this.root);
  TreeNode current;
  while ((current = queue.poll()) != null) {
    PrintTreeNames(current, queue);
  }
}

private void PrintTreeNames(TreeNode n, Queue<TreeNode> queue) {

  System.out.println(n.getData().getName());
  if (n.isDirectory()) {
    for (int i = 0; i < n.getChildren().size(); i++) {
      queue.add(n.getChildren().get(i));
    }
  }
}