二分木をレベル順または幅優先順でトラバースしながらレベルを追跡するにはどうすればよいですか?
バイナリ ツリーのノードには、左右の参照のみがあります。
ノードの各行を区別できるようにしたい。
レベル順トラバーサルの方法は次のとおりです。
private static Queue<Node> traverseLevelOrder(final Node node)
{
final Queue<Node> temporaryQueue = new LinkedList<Node>(); // Temporary queue is used for traversal.
final Queue<Node> permanentQueue = new LinkedList<Node>(); // Permanent queue is used for node storage.
// Add the root node, as current, to the queue.
Node current = node;
temporaryQueue.add(current);
permanentQueue.add(current);
while (!temporaryQueue.isEmpty())
{
current = temporaryQueue.remove();
System.out.println(String.valueOf(current));
// Check current's children.
if (current != null)
{
final Node left = current.getLeft();
final Node right = current.getRight();
current = left;
if (current != null)
{
temporaryQueue.add(current);
permanentQueue.add(current);
}
current = right;
if (current != null)
{
temporaryQueue.add(current);
permanentQueue.add(current);
}
}
}
return permanentQueue;
}