(ツリーの) 深さをコマンド ライン引数として指定した場合、どのようにツリーの反復を実装し、その深さで停止し、その深さでのみノードを順番に出力できますか?
ツリー構造:
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