简体   繁体   English

广度优先 N 叉树遍历

[英]Breadth-First N-ary tree traversal

I'm coding up an N-ary tree representation of file system hierarchies, which contains some information about the directories/files.我正在编写文件系统层次结构的 N 元树表示,其中包含有关目录/文件的一些信息。 Each node in the tree consists of a parent node, and a list of its children (if any) and is contained within a seperate Tree object.树中的每个节点都由一个父节点及其子节点(如果有)的列表组成,并包含在一个单独的 Tree 对象中。 This isn't the most eloquent method of implementing a tree as far as i'm aware, but I'm far enough into the project where it isn't worth going back.据我所知,这不是实现树的最有说服力的方法,但我已经深入到不值得回去的项目中。

public class TreeNode {

    private FileSystemEntry data;
    private TreeNode parent;
    private ArrayList<TreeNode> children;
    private boolean directory; //separates files from folders (files have no children) 

The tree structure is defined as its own separate object, since there will be several trees.树结构被定义为它自己的独立对象,因为将有几棵树。

public class DirectoryTree {

    private TreeNode Root;
    private int numNodes;
    private TreeNode Focus;

I understand that I will need to use a queue to add each node to while i traverse its children (or something similar).我知道在遍历其子节点(或类似的东西)时,我需要使用队列将每个节点添加到其中。

Here's a Depth first recursive solution that prints the names of each file/directory, just for reference.这是一个深度优先的递归解决方案,它打印每个文件/目录的名称,仅供参考。

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());
    }

}

I feel like it should only be a small modification to get from depth first to breadth first but I can't seem to get my head round it我觉得从深度优先到广度优先应该只是一个小的修改,但我似乎无法理解它

Create the queue initially with just the root node, process the queue until it is empty.最初只使用根节点创建队列,处理队列直到它为空。 To process a node output it first, then add all of it's children to the queue:要处理一个节点,首先输出它,然后将它的所有子节点添加到队列中:

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));
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM