2013-02-28 30 views
2

给定树的深度作为命令行参数,您如何实现遍历树的迭代并在该深度停止,然后仅在该深度打印节点?如何迭代树并在Java中打印特定深度的笔记?

树结构:

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 
+1

尝试过什么? – axiom 2013-02-28 11:59:58

+0

@axiom是的,我将用我迄今为止已经尝试过的代码编辑问题 - 我得到的输出只是按字母顺序从测试文件的所有行迭代。 – user2112464 2013-02-28 12:05:29

+0

树结构是什么样的? – Thomas 2013-02-28 12:06:24

回答

1

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

0

您显然需要做一个BFS。 但是,恐怕您无法从JDK获得足够的TreeSet或任何其他数据结构的内部结构。

因此,您需要实现您自己的树型数据结构(或使用第三方库)。

+0

这就是为什么你只能实现遍历无序的非二叉树的原因。一个LinkedList或一个队列? – user2112464 2013-02-28 14:07:30

+0

@ user2112464我不确定我是否了解您的最新评论。 “LinkedList”或“Queue”不是树。我所说的只是'TreeSet'是一个高级对象,它提供了一个高级迭代器。您无法访问给定节点的子节点,因此您无法基于此实现BFS。我不认为有另一种JDK树状数据结构。 – rds 2013-02-28 14:37:20

+0

因此,在这种情况下,我需要创建沿线的树结构: '公共类树私人节点
公共树(T rootData)
根=新节点();
root.data = rootData;
根。children = new ArrayList >();
public static class Node
private T data;
private node parent;
private List > children;
' – user2112464 2013-02-28 22:12:31