给定一个(树的)深度作为命令行参数,您如何实现对树的迭代并在该深度停止,然后仅按顺序打印该深度的节点?
树结构:
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/