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

Ağaç DFS

Rehber 3 / 6 · Yol 3 / 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.

Maximum Depth of Binary Tree

Problem (restated)

Given the root of a binary tree, return its maximum depth (number of nodes along the longest root-to-leaf path).

Intuition

Depth(node) = 1 + max(depth(left), depth(right)); empty node has depth 0.

Approaches

Recursive DFS

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

Idea. Base null→0; return 1+max of children.

Walkthrough. Balanced tree of height 3 → answer 3.

Trade-offs. BFS level-count is equivalent; DFS is shortest to write.

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 maxDepth(root: TreeNode | null): number {
  if (!root) return 0;
  return 1 + Math.max(maxDepth(root.left), maxDepth(root.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 maxDepth(root: TreeNode | null): number {
  if (!root) return 0;
  return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}

Template connection

Tree DFS returning aggregated info to parent.

Reflection