sagelearnai

Binary Tree Level Order Traversal

Difficulty: Medium · Pattern: Trees & BST · LeetCode #102

Return the node values level by level, from top to bottom, each level listed left to right.

Examples

text
[3, 9, 20, null, null, 15, 7]  →  [[3], [9, 20], [15, 7]]
[1]                            →  [[1]]
[]                             →  []

Hints

  1. Breadth-first search visits nodes in level order.
  2. At the start of each level, the queue contains exactly that level's nodes, so record its length.

Approach

Use a queue seeded with the root. While it's non-empty, take size = len(queue). Pop exactly size nodes (one level), collecting their values and enqueueing their children. Append the collected values as one level. Each node is enqueued and dequeued once.

Complexity

Time: O(n). Space: O(w), where w is the maximum width of the tree.

Python solution
from collections import deque

def levelOrder(root):
    if not root:
        return []
    out, q = [], deque([root])
    while q:
        level = []
        for _ in range(len(q)):
            node = q.popleft()
            level.append(node.val)
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
        out.append(level)
    return out
JavaScript solution
function levelOrder(root) {
  if (!root) return [];
  const out = []; let q = [root];
  while (q.length) {
    const level = [], next = [];
    for (const node of q) {
      level.push(node.val);
      if (node.left) next.push(node.left);
      if (node.right) next.push(node.right);
    }
    out.push(level); q = next;
  }
  return out;
}