Skip to content
DSA Patterns
Menu
Language
Tree BFSLC #5154 of 6← PreviousNext →

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

Unverified
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
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 largestValues(root: TreeNode | null): number[] {
  if (!root) return [];
  const res: number[] = [];
  let level: TreeNode[] = [root];
  while (level.length) {
    const next: TreeNode[] = [];
    let m = -Infinity;
    for (const n of level) {
      m = Math.max(m, n.val);
      if (n.left) next.push(n.left);
      if (n.right) next.push(n.right);
    }
    res.push(m);
    level = next;
  }
  return res;
}
export function largestValues(root: TreeNode | null): number[] {
  if (!root) return [];
  const res: number[] = [];
  let level: TreeNode[] = [root];
  while (level.length) {
    const next: TreeNode[] = [];
    let m = -Infinity;
    for (const n of level) {
      m = Math.max(m, n.val);
      if (n.left) next.push(n.left);
      if (n.right) next.push(n.right);
    }
    res.push(m);
    level = next;
  }
  return res;
}

Template connection

Level snapshot, and the recorded value is the maximum in the snapshot.

Reflection

  • Walk one level and take that row’s maximum. Starting the max at 0 is wrong on a negative row; start from the first node.
  • An empty tree is an empty list. One node is that value. A tied maximum is written once.
  • Order inside the row does not matter. Children are still pushed left to right.
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 6
1/6

Largest value in each row of 1 / 3, 2 / 5, 3, 9. Same level BFS; the payload is a running max.

1q32539

rowMax = []

Key:CurrentActive rangeMatchSettled