Binary Tree Level Order Traversal, visualized step by step

Medium One of the Blind 75 interview problems (LeetCode 102). Technique: breadth-first search. Solution in Python, explained at every step.

The problem

You get the root of a binary tree. Return its values level by level: first the root, then the nodes one edge below it, then the next level, each level from left to right, as a list of lists.

Example: a root 5 with children 2 and 9, where 2 has a left child 1 and 9 has children 7 and 11, gives [[5], [2, 9], [1, 7, 11]].

The tree with root 5 and children 2 and 9; 2 has a left child 1, and 9 has the children 7 and 11. A grey band runs behind each level, with its values beside it: [5], [2, 9] and [1, 7, 11]. Under it: answer: [[5], [2, 9], [1, 7, 11]].
Each band is one level, and each level becomes one list.

Try it yourself first: LeetCode 102 ↗. Then step through the solution below.

Brute force

Find each node's depth with any traversal, then sort the values by depth, keeping left-to-right order inside a level: O(n log n). A depth-first search does better: it carries each node's depth down and adds the value to levels[depth] as it goes, in one pass, O(n), each level still filling left to right.

The key insight

The clue is in the words "level by level": the nodes nearest the root first, which is the order a queue gives. A queue hands nodes out in the order they went in. If each node, when it is taken out, puts its children in, the nodes come out level by level, left to right: this is breadth-first search on a tree.

To know where one level ends, read the queue's length before taking anything out and keep it as size: at that moment the queue holds exactly the next level, and its children all go in behind it. Take size nodes, and the level is complete.

Step by step

The player runs the code on the example. Press → for each step: the lines it runs light up in the code.

On a phone, Full screen keeps the picture and the code on one screen.

Binary Tree Level Order Traversal, step by step

Python

from collections import dequeclass TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, right def level_order(root):    if root is None:        return []    levels = []    queue = deque([root])    while queue:        level = []        size = len(queue)        for _ in range(size):            node = queue.popleft()            level.append(node.val)            if node.left:                queue.append(node.left)            if node.right:                queue.append(node.right)        levels.append(level)    return levels
All steps as text
  1. The tree has 5 at its root and three levels. Its values should come out level by level, left to right.
  2. The list levels starts empty. It will hold the values of each level, one list per level.
  3. The queue starts with the root, 5. Nodes go in at the left and come out at the right, in the same order.
  4. The loop takes the tree one level at a time: level starts empty.
  5. size is 1: the queue holds exactly this level, so the loop takes 1 node.
  6. Take 5 out of the queue into node.
  7. Add 5 to level.
  8. Its left child, 2, goes into the queue.
  9. Its right child, 9, goes into the queue.
  10. size nodes are taken: the level is complete. Add [5] to levels.
  11. A new level begins: level starts empty.
  12. size is 2: the queue holds exactly this level, so the loop takes 2 nodes.
  13. Take 2 out of the queue.
  14. Add 2 to level.
  15. Its left child, 1, goes into the queue. It has no right child.
  16. The second of 2 turns: take 9 out of the queue.
  17. Add 9 to level.
  18. Its left child, 7, goes into the queue.
  19. Its right child, 11, goes into the queue.
  20. size nodes are taken: the level is complete. Add [2, 9] to levels.
  21. A new level begins: level starts empty.
  22. size is 3: the queue holds exactly this level, so the loop takes 3 nodes.
  23. Take 1 out of the queue.
  24. Add 1 to level. It has no children.
  25. The second of 3 turns: take 7 out of the queue.
  26. Add 7 to level. It has no children.
  27. The last of 3 turns: take 11 out of the queue.
  28. Add 11 to level. It has no children.
  29. size nodes are taken: the level is complete. Add [1, 7, 11] to levels.
  30. The queue is empty, so every node was taken: return [[5], [2, 9], [1, 7, 11]].
  31. Each node went into the queue and out once: O(n) time. At most 3 waited at once: O(w), for a widest level of w nodes.
Binary Tree Level Order Traversal, step by step. Last step: Each node went into the queue and out once: O(n) time. At most 3 waited at once: O(w), for a widest level of w nodes.

Note

The queue in Python is collections.deque: popleft is O(1). A plain list's pop(0) moves every other element one place, O(n), which on a wide tree turns the whole traversal into O(n2). Java uses ArrayDeque, with offer and poll; C++ uses std::queue. Both must read the size before the loop, as size here: a loop that tests i < queue.size() reads it again after the children went in, and two levels run together.

Complexity

ApproachTimeSpace
Brute force: the depth of every node, then a sort by depthO(n log n)O(n)
Depth-first search, passing the depth downO(n)O(n)
Queue, level by level this pageO(n)O(n)
  • Time: O(n). Each node goes into the queue once and comes out once.
  • Space: O(n). The queue holds the end of one level and the start of the next: O(w) for a widest level of w nodes, which in a full tree is about half of them. The result itself has all n values. A depth-first search needs O(h) for its calls instead, h the height of the tree.

Edge cases

  • An empty tree: the first check returns an empty list.
  • A single node: one level with one value, [[5]].
  • A chain, like 3 with a left child 2 with a left child 1: every level holds one node, so the result is [[3], [2], [1]].

Try it: put Binary Tree Level Order Traversal together step by step

The blocks below are steps of Binary Tree Level Order Traversal in words, and one of them does not belong. Put the right ones in order and check: your algorithm runs on the example tree and on an empty tree, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.

Put Binary Tree Level Order Traversal together

Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. One of them doesn't belong. Each block keeps its indent: it runs inside the nearest line above it that ends in a colon.

Your algorithm

Blocks

Interview follow-up

What about zigzag order? Odd levels left to right, even levels right to left: run exactly the same loop and reverse every second level before adding it (or fill it from the other end with a deque). Still O(n) time and space. This is Binary Tree Zigzag Level Order Traversal (LeetCode 103).

Note

The same loop answers other problems by keeping one value per level: the last value of each level gives the tree's right side view (LeetCode 199), the average of each level's values gives the level averages (LeetCode 637), and stopping at the first level that has a leaf gives the minimum depth (LeetCode 111).

The data structure behind it