Given the roots p and q of two binary trees, return true if they are the same — identical in structure and with equal node values at every position — and false otherwise.
Each tree is given in level-order (breadth-first), using null for missing children.
Input: p = [1, 2, 3], q = [1, 2, 3] Output: true Same structure and same values at every position.
Input: p = [1, 2], q = [1, null, 2] Output: false The 2 is a left child in p but a right child in q — different structure.
Input: p = [1, 2, 1], q = [1, 1, 2] Output: false Same structure but the child values are swapped.
- The number of nodes in each tree is in the range [0, 100] - -10^4 <= Node.val <= 10^4
Two trees are the same when their roots match and their left subtrees are the same and their right subtrees are the same. That's the recursion. The base cases handle nulls: two nulls match; one null against a real node does not.
“What counts as 'same'?”
Identical shape and identical values at every corresponding position.
“Are two empty trees the same?”
Yes — both null is a match.
Two trees are the same if the roots have equal values and their left and right subtrees are pairwise the same.
I recurse over both trees together; the base cases are two nulls (equal) and one null versus a node (not equal).
Worked example — p = [1, 2, 3], q = [1, 2, 3]
compare 1 vs 1 ✓ -> compare left (2 vs 2) and right (3 vs 3) 2 vs 2 ✓ (both children null) ; 3 vs 3 ✓ answer: true
The recursion mirrors the definition exactly; the AND of the two subtree comparisons is the crux.
Two nulls → equal; one null and one node → structurally different, so not equal.
Each corresponding node pair is compared once (O(n)); recursion depth is O(height).
| Iterative (queue of pairs) | Recursive | |
|---|---|---|
| Idea | Compare node pairs from a queue in lockstep | roots equal AND left same AND right same |
| Time | O(n) | O(n) |
| Space | O(n) | O(height) |
Both are O(n); the recursion is a direct transcription of the definition. Full code is in the Approaches selector below.
Key takeaway
Two trees are the same iff their roots are equal and both subtrees are pairwise the same. Handle the null base cases, then AND the recursive results. O(n) time, O(height) space.
same(p, q):
if p is null and q is null: return true
if p is null or q is null or p.val != q.val: return false
return same(p.left, q.left) and same(p.right, q.right)