Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Trees

Same Tree

EASY✓ CHIP-TIMEDLC #100 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Decide whether two binary trees are identical — same values arranged in exactly the same shape, not just the same values somewhere.

Two binary trees arrive, and the task is to decide whether they're truly identical — the same values arranged in exactly the same shape, node for node.

Matching values alone isn't enough: a node present in one tree but missing in the other at the corresponding spot breaks the match, even if every value that does exist lines up perfectly.

Two empty trees count as identical to each other, and an empty tree never matches a non-empty one, no matter what values the non-empty one holds.

  • either or both trees can be empty
  • each tree can hold up to a few thousand nodes
  • node values can be negative, zero, or positive
  • shape must match exactly — a missing child on one side is a mismatch
EX 01
p = [] · q = []
→ true
two empty trees
EX 02
p = [] · q = [1]
→ false
empty against a single node
EX 03
p = [1] · q = [1]
→ true
matching single nodes

The hintstake only what you need

HINT 1 THE NUDGE

Two trees match only if their roots match AND both pairs of children match. What's a direct way to encode 'the whole shape' so two encodings can just be compared?

HINT 2 THE STRUCTURE

A preorder walk that writes down a null marker for every missing child pins down a tree's shape uniquely — two trees are identical exactly when that encoding is identical.

HINT 3 ONE STEP FROM THE ANSWER

You don't have to build the encoding at all: compare the two roots directly, and the moment one node's value or presence disagrees with the other, stop and report false right there.

Coach's boardthe pattern, step by step

THE PAIRED WALKPATTERN · PAIRED RECURSIONp = [1, 2] · q = [1, null, 2]
STEP 1

Same shape AND same values, node for node. Compare root to root first: tree1's root is 1, tree2's root is 1 — match.

STEP 1 / 5 · ← → WORK TOO

The splitstwo paces, two languages

grind/same-tree.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p and not q:
            return True
        if not p or not q:
            return False
        if p.val != q.val:
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
TIME O(N)SPACE O(H)PYTHON · RACE PACE · 9 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED