6.3Binary Tree with Linked Nodes
Level-order traversal: with a queue
Preorder, inorder and postorder dive into the depth of the tree: they finish one branch before moving to another. A level-order traversal reads the tree layer by layer instead: the root, then the root's children, then the grandchildren, left to right on each level. This order comes from a queue, not from recursion. On the sample tree the output is 10 20 30 40 50 60.
- How level order differs from the other traversals
- Why the queue hands out the upper level before the lower one
- How many nodes the queue can hold at most
1Idea
The root goes into the queue. On each turn of the loop the front node is taken out and printed, then its left and right children, if any, go to the back of the queue. The queue works first in, first out, so all the nodes on one level leave the queue before their children. When the queue is empty, every node has been printed.
This function is the same search as in the insertion lesson; there it stopped at the first missing child, here it goes to the end and prints every node. Swap the queue for a stack and the order is no longer level order: you get a depth-first walk that looks like preorder.
In graphs the same method is called breadth-first search (BFS). Questions like the shortest path in a tree, that is how many steps it takes to reach a value, printing a tree level by level and finding the largest value on each level are solved with this traversal. In an array tree the same order is just reading the array from start to end; not even a queue is needed.
In the C version the queue is a 100-element array inside the function, so the tree can have at most 100 nodes. Removed elements stay at the start of the array; bigger trees need a circular queue or one built with a linked list.
2Step by step
The drawing walks the sample tree in level order. The contents of the queue are shown under the drawing, with the front on the left. n is the node just taken out and printed; the green ones were printed earlier.
- Start. The tree is not empty; the queue is still empty.
- The root goes into the queue. Queue: 10.
- 10 is taken out and printed. Its children 20 and 30 join the queue. Output: 10.
- The front, 20, is taken out and printed; its children 40 and 50 go to the back. 30 is still at the front. Output: 10 20.
- 30 is taken out and printed; its left child 60 joins the queue, its right is NULL. Level 1 is done. Output: 10 20 30.
- 40 is taken out and printed. It has no children, so nothing joins the queue. Output: 10 20 30 40.
- 50 is taken out and printed. Output: 10 20 30 40 50.
- 60 is taken out and printed. The queue is empty and the loop ends. Output: 10 20 30 40 50 60.
- Level order: 10, then 20 30, then 40 50 60.
struct TreeNode { int data; struct TreeNode* left; struct TreeNode* right;}; void levelOrder(struct TreeNode* root) { if (root == NULL) return; // empty tree struct TreeNode* queue[100]; int front = 0, rear = 0; queue[rear++] = root; while (front < rear) { struct TreeNode* n = queue[front++]; // take the front one printf("%d ", n->data); if (n->left != NULL) queue[rear++] = n->left; if (n->right != NULL) queue[rear++] = n->right; }}class TreeNode { int data; TreeNode left, right; TreeNode(int data) { this.data = data; }} void levelOrder(TreeNode root) { if (root == null) return; // empty tree java.util.ArrayDeque<TreeNode> queue = new java.util.ArrayDeque<>(); queue.add(root); while (!queue.isEmpty()) { TreeNode n = queue.poll(); // take the front one System.out.print(n.data + " "); if (n.left != null) queue.add(n.left); if (n.right != null) queue.add(n.right); }}from collections import deque class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def level_order(root): if root is None: # empty tree return queue = deque([root]) while queue: n = queue.popleft() # take the front one print(n.data, end=" ") if n.left is not None: queue.append(n.left) if n.right is not None: queue.append(n.right)The snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Every node enters the queue once and leaves it once.
The queue holds most of a level at once. The last level of a complete tree has about n/2 nodes.
Depth-first traversals take O(h) room. On a balanced, wide tree level order needs more memory; on a tree that is a single branch the queue never holds more than one node.
4Common mistake
A common mistake is putting the children into the queue without checking whether they are NULL:
queue[rear++] = n->left; // NULL can get in tooqueue[rear++] = n->right;Then NULL values enter the queue, and on a later turn n->data is read through NULL; the program crashes. Either check each child before adding it, or skip the turn with continue when the node taken out is NULL. Another mistake is putting the root into the queue when the tree is empty: the first turn reads the value of a NULL node.
5Try it
A tree has root 1, left child 2, right child 3; 4 is the left child of 2 and 5 is the right child of 3. What is its level order?
The answer is B. First level 0: 1. Then level 1, left to right: 2 3. Then level 2: 4 and 5.
Show the answer
The answer is B. First level 0: 1. Then level 1, left to right: 2 3. Then level 2: 4 and 5.
In the sample tree, which values are in the queue right after 20 is printed?
The answer is B. After 10 left, the queue held 20 and 30. 20 left and was printed, and its children 40 and 50 went to the back, while 30 stayed at the front.
Show the answer
The answer is B. After 10 left, the queue held 20 and 30. 20 left and was printed, and its children 40 and 50 went to the back, while 30 stayed at the front.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.