Skip to content
DSA Patterns
Menu
Language
Tree BFSLC #1021 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Mediumtree-bfs

Binary Tree Level Order Traversal

Problem (restated)

Return the level order traversal of a binary tree values (left to right, level by level).

Intuition

Queue; process exact level size each round.

Approaches

Level BFS

Unverified
Time O(n)Space O(w)

Idea. BFS with size snapshot per level.

Walkthrough. [3,9,20,null,null,15,7] → [[3],[9,20],[15,7]].

Trade-offs. BFS natural; DFS with depth lists also works.

Solution
Show helper code
export class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val; this.left = left; this.right = right;
  }
}
export class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val; this.left = left; this.right = right;
  }
}
export function levelOrder(root: TreeNode | null): number[][] {
  if (!root) return [];
  const res: number[][] = [];
  let level: TreeNode[] = [root];
  while (level.length) {
    const next: TreeNode[] = [];
    const vals: number[] = [];
    for (const n of level) {
      vals.push(n.val);
      if (n.left) next.push(n.left);
      if (n.right) next.push(n.right);
    }
    res.push(vals);
    level = next;
  }
  return res;
}
export function levelOrder(root: TreeNode | null): number[][] {
  if (!root) return [];
  const res: number[][] = [];
  let level: TreeNode[] = [root];
  while (level.length) {
    const next: TreeNode[] = [];
    const vals: number[] = [];
    for (const n of level) {
      vals.push(n.val);
      if (n.left) next.push(n.left);
      if (n.right) next.push(n.right);
    }
    res.push(vals);
    level = next;
  }
  return res;
}

Template connection

Level lists: snapshot the queue length, pop that many nodes, and enqueue their children. One snapshot is one level, left to right.

Reflection

  • The level size is the queue length at the start of the round. Counting children in that same round mixes levels.
  • A null root is an empty list. One node is one row. Children are pushed left to right.
  • Pushing the right child first scrambles the row. There is no empty level.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 8
1/8

Tree BFS is still a real tree. Queue starts with the root only.

3q920157
Statequeue=[3]level=0

queue = [3] · level 0

Key:CurrentActive rangeMatchSettled