给定树的深度作为命令行参数,您如何实现遍历树的迭代并在该深度停止,然后仅在该深度打印节点?如何迭代树并在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
尝试过什么? – axiom 2013-02-28 11:59:58
@axiom是的,我将用我迄今为止已经尝试过的代码编辑问题 - 我得到的输出只是按字母顺序从测试文件的所有行迭代。 – user2112464 2013-02-28 12:05:29
树结构是什么样的? – Thomas 2013-02-28 12:06:24