java - Java中如何遍历树并在一定深度打印注释?

标签 java tree

给定一个(树的)深度作为命令行参数,您如何实现对树的迭代并在该深度停止,然后仅按顺序打印该深度的节点?

树结构:

    Root:        A       (Depth)   0
              /     \
           C           B           1
         / | \        / \
        E  D  F      G   H         2

示例输出: 深度 = 0 输出 = A

深度 = 1 输出 = B,C

深度 = 2 输出 = D,E,F,G,H

据我所知,遍历树结构的唯一方法是 while(iterator.hasNext()) 循环 - 但是,如果我尝试在此循环中打印树的节点,它将打印节点在那个级别和它前面的节点,这不是我想要的。

编辑:初始代码

    public static void main(String[] args)
    {
     int depth;
     BufferedReader input = null;

     try
     {
      input = new BufferedReader(new FileReader(args[0]));
      depth = Integer.parseInt(args[1]);

      String currentLine = "";
      TreeSet<String> lineSet;
      lineSet = new TreeSet<String>();
      while((currentLine = input.readLine()) != null)
      {
       lineSet.add(currentLine);   
      }
      Iterator<String> iterator;
      iterator = lineSet.iterator();
      while (iterator.hasNext())
      {
       System.out.println(iterator.next());
      } // while
     } // try
     catch(IOException exception)
     {
      System.err.println(exception);
     } // catch
     finally
     {
      try{ if (input != null) input.close(); }
      catch (IOException exception)
      { System.err.println("Could not close input " + exception); }
      } // finally
     } // main

最佳答案

好吧,基本上你按广度优先顺序遍历树,直到达到你想要的深度。然后开始打印出节点或将它们收集到一个列表/集合中,稍后再打印出来。

关于java - Java中如何遍历树并在一定深度打印注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15134960/

相关文章:

java - 将数据从 java gui 输入到现有的 Excel 电子表格

c++ - 逐级遍历父数组n叉树?

c# - 在树中搜索算法

c# - 如何根据字符串表示形式创建表示命名空间的树

Java字符串识别

java - 关闭 Intent 导航谷歌并返回我的应用程序

java - 使用curl输出http状态码、总时间和请求体

java - 在 ArrayList 中的 foreach 循环内添加时出现 ConcurrentModificationException

python - 未知的循环次数

java - 为什么当我使用 HttpClient 时,分块流会意外结束?