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

Ağaç DFS

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

Same Tree

Problem (restated)

Check whether two binary trees are structurally identical with the same values.

Intuition

Both null equal; one null not; values equal and recurse children.

Approaches

Recursive DFS

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

Idea. isSame(p,q) = p.val==q.val and isSame left and right.

Walkthrough. Identical shapes and values → true.

Trade-offs. DFS recursion vs BFS pair queue.

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 isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
  if (!p && !q) return true;
  if (!p || !q || p.val !== q.val) return false;
  return isSameTree(p.left, q.left) && isSameTree(p.right, q.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 isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
  if (!p && !q) return true;
  if (!p || !q || p.val !== q.val) return false;
  return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}

Template connection

Tree DFS return bool.

Reflection