Tree BFS

Trees & Graphs

Signal

Level order, min depth, width per level

Template

Process one whole level at a time with a queue.

Worked example (1)

#11

Tree BFS

BFS

Return the values of a binary tree grouped level by level, top to bottom.

function levelOrder(root: TreeNode | null): number[][] {
  const res: number[][] = [];
  if (!root) return res;
  let level: TreeNode[] = [root];
  while (level.length) {
    const vals: number[] = [];
    const next: TreeNode[] = [];
    for (const node of level) {
      vals.push(node.val);
      if (node.left) next.push(node.left);
      if (node.right) next.push(node.right);
    }
    res.push(vals);
    level = next;
  }
  return res;
}
Insight

Swapping whole levels avoids tracking per-node depth.