Breadth-first Traversal
In breadth-first traversal (also called level-order traversal or
generational traversal), we traverse the tree generation by generation,
from left to right. For example, for the binary tree below, we start at the
first generation, which has only one node, the root n(a).
Then we start at the next generation, visiting from the left:
to the right:
Hence, for generational traversal, we have the traversal sequence For a left-skewed tree, we have the traversal sequence
And for a right-skewed tree, we have the traversal sequence
Implementation
Consider the following tree (edge labels are pointer values):
In level-order traversal, we traverse the tree's nodes level by level. Thus, for the tree above, we have the traversal:
As with the other traversal methods, we can implement level-order traversal the tree by making use of queue.
fn levelOrder(Node* root) -> void:
Queue qeueue = newQueue();
print((*root).data)
enqueue(qeueue, root);
while (!isEmpty(q)):
root = dequeue(qeueue);
if ((*root).leftChild):
print((*(*root).leftChild).data);
enqueue(queue, (*root).leftChild);
if ((*root).rightChild):
print((*(*root).rightChild).data);
enqueue(queue, (*root).rightChild);
Here's a line by line summary of the code above:
- Declare the function.
- Create a new empty queue.
- Print the root's data. This is the first node in the tree, the root node.
- Enqueue root to the queue.
- As long as the queue is not empty, execute the following instructions. If the queue is empty, END.
- Dequeue the queue, and make root the dequeued value (a node).
- If the dequeued node has a left child, execute the instructions below. Otherwise, go to instruction 9.
- Print the dequeued node's data.
- Enqueue the left child of the dequeued node to the queue.
- If the dequeued node has a right child, execute the instructions below. Otherwise, go back to instruction 4.
- Print the dequeued node's data. Enqueue the right child of the dequeued node to the queue.