◀ THE GRIND — TREES

Same Tree

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

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

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.

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 HINTS — TAKE 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 BOARD — THE 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 SPLITS — TWO PACES, TWO LANGUAGES
grind/same-tree.pyRACE 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-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED