Binary Tree Level Order Traversal0/59 done
Part 2 · Problems · Trees and BFS

Binary Tree Level Order Traversal

#102 · Medium · LeetCode

Return node values level by level, left to right.

[3,9,20,null,null,15,7] -> [[3],[9,20],[15,7]]

Ask before coding

Hint

BFS: process one whole level, collect the next level.

Approach

Start with [root]. Record its values. Build the next level from the children. Repeat until empty.

Time O(n)   Space O(w), w = widest level

Watch it run
Solution (JavaScript, tested)
function levelOrder(root) {
  if (!root) return [];
  const out = [];
  let level = [root];
  while (level.length) {
    out.push(level.map(n => n.val));
    const next = [];
    for (const n of level) {
      if (n.left) next.push(n.left);
      if (n.right) next.push(n.right);
    }
    level = next;
  }
  return out;
}

Traps

Say out loud: Breadth-first. I process a full level at a time so grouping comes for free.