How to keep track of the level while traversing a binary tree in level order or breadth-first order?
The nodes in the binary tree have left and right references only.
I want to be able to distinguish between each row of nodes.
Here is my method for level-order traversal:
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;
}
It is possible to keep track of the level when you know that the number of nodes doubles each level.
For example, in level 0, there is only 1 node; in level 1, there are 2 nodes; in level 2, there are 4 nodes; in level 3, there are 8 nodes; in level 4, there are 16 nodes; etc.
The code for grouping each level of nodes into an array using level-order traversal in Java may look like this:
It checks the number of nodes on the current level. When the nodes have filled the current level, then it starts a new level.
As an example, a binary tree may look like this:
Here is the output of the example:
Here is the JavaScript version: