Binary Tree Level Order Traversal

Return the level order traversal of a binary tree.

Pattern

BFS Queue

This problem follows the BFS Queue pattern, commonly found in the Trees category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Use a queue. Process all nodes at current level, add their children for next level.

Key Insight

Capturing queue size at the start of each iteration lets you process exactly one level at a time — this is the BFS level-order trick.

Step-by-step

  1. 1Create a queue and add the root
  2. 2While the queue is not empty:
  3. 3Record the current queue size (= nodes at this level)
  4. 4Process all nodes at this level, adding their children to the queue
  5. 5Add the level's values to the result

Pseudocode

result = []
queue = deque([root])
while queue:
    level = []
    for _ in range(len(queue)):
        node = queue.popleft()
        level.append(node.val)
        if node.left: queue.append(node.left)
        if node.right: queue.append(node.right)
    result.append(level)
return result
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)
More Trees Problems

Master this pattern with YeetCode

Practice Binary Tree Level Order Traversal and similar Trees problems with flashcards. Build pattern recognition through active recall.

Practice this problem