İçeriğe atla
ΣDSA Patterns
Menü
Dil

Ağaç BFS

Rehber 4 / 6 · Yol 4 / 6

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

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