LeetCode #100 Easy

Same Tree

Are two binary trees structurally identical with equal values?

treedfsrecursion
Open on LeetCode ↗
02

Intuition

Two trees are the same iff their roots match and both subtree pairs are the same — the definition is the recursion. Base cases: both empty (true), one empty (false).

How to spot this pattern

The template for comparing two trees in lockstep: recurse on both at once, and let the base cases carry all the work. Any structural question — same tree, symmetric tree, subtree of another tree — comes down to deciding what "both null", "one null", and "both present" should mean.

03

Approach

1

Compare roots, recurse in parallel

p.val == q.val AND same(p.left, q.left) AND same(p.right, q.right).

2

Null logic first

Both None → True. Exactly one None → False. This catches structural mismatches before touching values.

3

Short-circuit

The and-chain stops at the first mismatch — no wasted traversal.

04

Solution & live demo

1class Solution:
2 def isSameTree(self, p, q):
3 if not p and not q: return True
4 if not p or not q: return False
5 return (p.val == q.val
6 and self.isSameTree(p.left, q.left)
7 and self.isSameTree(p.right, q.right))
05

Common pitfalls

Checking not p or not q before not p and not q

✗ Wrong
if not p or not q: return False
if not p and not q: return True
✓ Right
if not p and not q: return True
if not p or not q: return False

Two empty trees satisfy both conditions, so with the order reversed the first line fires and reports False for a pair of identical empty subtrees — which every leaf has two of. The order encodes the priority: agreement first, then mismatch.

Comparing values before checking for null

✗ Wrong
if p.val != q.val: return False
✓ Right
if not p and not q: return True
if not p or not q: return False
return p.val == q.val and ...

The moment either side runs out of nodes, p.val raises AttributeError. Structure has to be settled before values are read.

06

Edge cases

Same values, different shape, e.g. [1,2] vs [1,null,2]

One side hits None-vs-node → False.

Both empty

Vacuously identical → True.

07

Complexity

Time
O(n)
Space
O(h)
Visits each pair once.