Skip to content
ΣDSA Patterns
Menu
Language

Tree BFS

Guide 4 of 6 · Path 4 of 6

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

Mediumtree-bfs

Find Largest Value in Each Tree Row

Problem (restated)

Return an array of the largest value in each level of a binary tree.

Intuition

Standard level BFS; track max while scanning each level size.

Approaches

Level BFS max

Tested only
Time O(n)Space O(w)

Idea. For each level, max over the level array.

Walkthrough. Levels [1], [3,2], [5,3,9] → [1,3,9].

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

Solution
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 largestValues(root: TreeNode | null): number[] {
  if (!root) return [];
  const res: number[] = [];
  const q: TreeNode[] = [root];
  while (q.length) {
    const size = q.length;
    let m = -Infinity;
    for (let i = 0; i < size; i++) {
      const n = q.shift()!;
      m = Math.max(m, n.val);
      if (n.left) q.push(n.left);
      if (n.right) q.push(n.right);
    }
    res.push(m);
  }
  return res;
}
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 largestValues(root: TreeNode | null): number[] {
  if (!root) return [];
  const res: number[] = [];
  const q: TreeNode[] = [root];
  while (q.length) {
    const size = q.length;
    let m = -Infinity;
    for (let i = 0; i < size; i++) {
      const n = q.shift()!;
      m = Math.max(m, n.val);
      if (n.left) q.push(n.left);
      if (n.right) q.push(n.right);
    }
    res.push(m);
  }
  return res;
}

Template connection

Tree BFS per-level aggregate.

Reflection