Skip to content
DSA Patterns
Menu
Language
Tree DFSLC #1002 of 6← PreviousNext →

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

Unverified
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
Show helper code
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 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 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

Both roots walk together. Two nulls match. One null fails. Otherwise the values are equal and both child pairs match. The function returns that bool.

Reflection

  • Both null is true. One null is false. Do the values match, and both children?
  • A mirror image is not the same tree. The same shape with a different value is false.
  • Two empty trees are equal.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 7
1/7

Same tree? Compare p=[1,2,3] with q=[1,2,3] node by node: value and structure.

1p231q23

both null = equal · one null = not

Key:CurrentActive rangeMatchSettledEliminated