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

Ağaç DFS

Rehber 4 / 6 · Yol 4 / 6

Interactive

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 / 8
3920157

post-order: children first, then me

Tree DFS walks structure, not a flat list. Root 3, left 9, right subtree 20 → 15, 7.

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.

Balanced Binary Tree

Problem (restated)

A height-balanced tree has |leftHeight, rightHeight| ≤ 1 at every node. Check if the tree is balanced.

Intuition

Return height from each subtree; if either side is unbalanced or heights differ by >1, bubble a sentinel.

Approaches

Height + flag DFS

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

Idea. height(node): if either child returns -1 or |hl-hr|>1 return -1; else 1+max.

Walkthrough. Perfect small trees ok; a long chain on one side fails.

Trade-offs. Single DFS O(n) vs naive recompute height O(n²).

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 isBalanced(root: TreeNode | null): boolean {
  const height = (node: TreeNode | null): number => {
    if (!node) return 0;
    const hl = height(node.left);
    if (hl < 0) return -1;
    const hr = height(node.right);
    if (hr < 0) return -1;
    if (Math.abs(hl - hr) > 1) return -1;
    return 1 + Math.max(hl, hr);
  };
  return height(root) >= 0;
}
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 isBalanced(root: TreeNode | null): boolean {
  const height = (node: TreeNode | null): number => {
    if (!node) return 0;
    const hl = height(node.left);
    if (hl < 0) return -1;
    const hr = height(node.right);
    if (hr < 0) return -1;
    if (Math.abs(hl - hr) > 1) return -1;
    return 1 + Math.max(hl, hr);
  };
  return height(root) >= 0;
}

Template connection

Tree DFS multi-field return.

Reflection