Skip to content
ΣDSA Patterns
Menu
Language

Tree DFS

Guide 2 of 6 · Path 2 of 6

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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