İçeriğe atla
DSA Patterns
Menü
Dil
Ağaç BFSLC #6375 / 6← ÖncekiSonraki →

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

Average of Levels in Binary Tree

Problem (yeniden ifade)

Her seviyedeki düğümlerin ortalama değerini double dizisi olarak döndür.

Sezgi

Seviye BFS; her seviye için sum/count.

Yaklaşımlar

Seviye BFS ortalama

Doğrulanmadı
Zaman O(n)Alan O(w)

Fikir. Her seviye boyutu için toplamı biriktir, sum/size ekle.

Yürüyüş. [3,9,20,null,null,15,7] → [3, 14.5, 11].

Trade-off. Seviye sırası ile aynı iskelet; yalnızca toplulaştırma farklı.

Çözüm
Yardımcı kodu göster
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 averageOfLevels(root: TreeNode | null): number[] {
  if (!root) return [];
  const res: number[] = [];
  let level: TreeNode[] = [root];
  while (level.length) {
    const next: TreeNode[] = [];
    let sum = 0;
    for (const n of level) {
      sum += n.val;
      if (n.left) next.push(n.left);
      if (n.right) next.push(n.right);
    }
    res.push(sum / level.length);
    level = next;
  }
  return res;
}
export function averageOfLevels(root: TreeNode | null): number[] {
  if (!root) return [];
  const res: number[] = [];
  let level: TreeNode[] = [root];
  while (level.length) {
    const next: TreeNode[] = [];
    let sum = 0;
    for (const n of level) {
      sum += n.val;
      if (n.left) next.push(n.left);
      if (n.right) next.push(n.right);
    }
    res.push(sum / level.length);
    level = next;
  }
  return res;
}

Şablon bağlantısı

Seviye fotoğrafı. Kaydedilen değer, o turda pop edilen düğümlerin toplamının turun boyutuna bölümüdür.

Yansıma

  • Seviye toplamı bölü seviye boyu. Tam sayı bölme ortalamayı keser.
  • Negatif değerler toplamı düşürür. Tek düğüm kendisi. Boş ağaç boş.
  • Büyük toplam int’i taşırabilir. Toplamı geniş tut.
Katkıda bulunan inceleme listesi

Etkileşimli

Zihinsel model

Bu problem için animasyonlu çözüm. Adımları kaydır veya boşlukla duraklat; değişmezi yüksek sesle yeniden anlat.

Adım 1 / 6
1/6

3 / 9, 20 / 15, 7 her seviyesinin ortalaması. Seviye BFS; yük sum / count.

3q920157

avg = []

Gösterim:GüncelAktif aralıkEşleşmeTamam