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