Same Tree
Given the roots of two binary trees p and q, return true if they are identical: the same shape and the same value at every corresponding position. Two empty trees are identical. A tree is not identical to one that merely holds the same values in a different arrangement.
- The number of nodes in each tree is in the range [0, 100]
- -10⁴ <= Node.val <= 10⁴
- Both structure and values must match
- Either tree may be empty
p = [1,2,3], q = [1,2,3]truep = [1,2], q = [1,null,2]falsep = [1,2,1], q = [1,1,2]falsep = [], q = []trueTwo trees are "the same" when they have the exact same shape and the same value at every matching spot. The trick: don't walk one tree — walk both at once, one foot in each, always standing on the same position in both.
p: 1 q: 1
/ \ / \
2 3 2 3 step through both together, same turnsAt every step you're standing on a pair — a from tree p, b from tree q, at matching positions. Four things can happen:
p: 1 q: 1
/ \
2 2 p's 2 is a LEFT child, q's is a RIGHT child
left pair = (2, null) -> one null -> FALSEdef isSame(p, q):
if p is None and q is None:
return True # both stop here, same way
if p is None or q is None:
return False # one stops, one doesn't — shape differs
if p.val != q.val:
return False # value differs
return isSame(p.left, q.left) and isSame(p.right, q.right)p is None or q is None line is also true when both are null, so if it ran first it would wrongly return false for two empty spots. In this order, reaching line 3 guarantees both nodes exist, so p.val is safe to read. The and also short-circuits: the moment the left pair disagrees, the right pair is never looked at, and the false shoots straight up.p = [1,2,1], q = [1,1,2] — same shape, values swapped:
p: 1 q: 1 roots match (1 = 1)
/ \ / \
2 1 1 2
left pair: (2, 1) -> values differ -> FALSE
right pair: never checked (the AND already collapsed)Answer false — and note comparing sorted contents would wrongly pass this, since both hold {1,1,2}. Position matters.
Worst case every position is compared once: O(min(N, M)) time (the walk stops as soon as one tree runs out), O(H) stack. The reusable shape is the paired recursion: when a question is about two structures, recurse on both together and let a local disagreement at any pair settle it. The skeleton is fixed — both-empty, one-empty, local check, then paired recursive calls — and only the local check and the pairing change from problem to problem.
Same Tree Audit
Parallel Structure Verification
Checking root values. Both are 1.
"Both Null? True. Diff Vals? False."
Strategy
Parallel traversal ensures structural equality. catch differences immediately.
"Base-case focused recursion."