LeetCode #100 Easy

Same Tree

Same Tree is LeetCode 100 (Easy). You get the roots p and q of two binary trees. Return true if they are the same tree and false otherwise.

  • Same means the same shape, with equal values at every matching position.
  • Either tree can be empty, and each has at most 100 nodes.
Constraints
  • The number of nodes in both trees is in the range [0, 100].
  • -10⁴ <= Node.val <= 10⁴
treedfsrecursion
Open on LeetCode ↗
02

Intuition

Two identical binary trees agree in three ways: their roots hold the same value, their left subtrees are identical, and their right subtrees are identical. The last two are the same question asked about smaller trees, so the whole check is one recursive function on a pair of nodes in the same position.

  • Both missing: there is nothing to differ, so the pair matches.
  • One missing: one tree has a node where the other has none, so the shapes differ.
  • Both present: the values must be equal, and then both child pairs must match.

The first mismatch anywhere decides the answer, so the walk stops there.

How to spot this pattern

When a question asks whether two trees match position by position, walk them together and compare one pair of nodes per call. The base cases are where shape differences show up.

03

Approach

Try it first

Before reading on, list every way a pair of nodes can look (both missing, one missing, both present) and decide the answer for each. Aim for a single walk over both trees.

1

Settle the missing nodes first

If p and q are both null, return true: two empty subtrees are equal. If exactly one is null, return false. Checking the two-null case first matters, because the one-null test would also fire on two nulls. After both checks, reading .val is safe.

2

Compare the two values

With both nodes present, compare p.val and q.val. If they differ, return false without looking at either subtree: whatever lies below, the trees already disagree at this position.

3

Recurse on the left pair, then the right pair

Return the result for (p.left, q.left) and the result for (p.right, q.right). Each call gets two nodes in the same position, so a false from any depth travels straight back up to the root.

4

Why the first false ends the walk

and skips its right side once the left side is false, so a failing left pair means the right pair is never visited. The slow case is two trees that really are identical: then every pair of nodes gets checked exactly once.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
▶3 if p is None and q is None:
▶4 return True
▶5 if p is None or q is None:
▶6 return False
▶7 if p.val != q.val:
▶8 return False
▶9 return (self.isSameTree(p.left, q.left)
▶10 and self.isSameTree(p.right, q.right))
tree ptree q123123both 1 → compare the children
p1
q1
Both trees have 1 at the root. That settles this position; now the left pair and then the right pair must match too.
tree ptree q123123both 2 → compare the children
p2
q2
Both trees have 2 at the same spot, 1 level down. That settles this position; now the left pair and then the right pair must match too.
tree ptree q123123both empty here → match
pnull
qnull
Both trees have no node in this spot. Two empty subtrees are equal, so this call returns true without reading any value.
tree ptree q123123both empty here → match
pnull
qnull
Both trees have no node in this spot. Two empty subtrees are equal, so this call returns true without reading any value.
tree ptree q123123both 3 → compare the children
p3
q3
Both trees have 3 at the same spot, 1 level down. That settles this position; now the left pair and then the right pair must match too.
tree ptree q123123both empty here → match
pnull
qnull
Both trees have no node in this spot. Two empty subtrees are equal, so this call returns true without reading any value.
tree ptree q123123both empty here → match
pnull
qnull
Both trees have no node in this spot. Two empty subtrees are equal, so this call returns true without reading any value.
tree ptree q123123every pair matched → true
resulttrue
Every call returned true: each position has a node in both trees with the same value, and every empty spot is empty in both. The trees are the same.
05

Common pitfalls

Pairing left with right

✗ Wrong
return (self.isSameTree(p.left, q.right)
        and self.isSameTree(p.right, q.left))
✓ Right
return (self.isSameTree(p.left, q.left)
        and self.isSameTree(p.right, q.right))

Crossing the children tests whether one tree is the mirror of the other, which is Symmetric Tree's check. p = [1,2,3], q = [1,3,2] returns true, and two copies of [1,2,3] return false.

Joining the subtree results with or

✗ Wrong
return (self.isSameTree(p.left, q.left)
        or self.isSameTree(p.right, q.right))
✓ Right
return (self.isSameTree(p.left, q.left)
        and self.isSameTree(p.right, q.right))

With or, one matching side is enough. p = [1,2,3], q = [1,2,4] returns true because the left subtrees match, even though the right children differ.

06

Edge cases

Both trees empty, p = [], q = []

The first check sees two nulls and returns true at once.

One tree empty, p = [], q = [0]

The second check returns false before any value is read, so there is no null dereference.

07

Complexity

Time
O(n)
Space
O(h)
n is the size of the smaller tree, because the walk stops where one tree runs out of nodes. h is the height: the recursion is about log n calls deep in a balanced tree and n deep in a 100-node chain.
08

Same Tree FAQ

Can you compare the two traversals instead?

Only if the traversal also records the empty children. The plain preorder of [1,2] and of [1,null,2] is 1, 2 for both, yet the shapes differ. Writing # for every null gives 1 2 # # # and 1 # 2 # #, which do differ, but the direct pair walk does the same job without building any strings.

Can it be solved without recursion?

Yes. Push the pair (p, q) onto a stack, then pop a pair, run the same three checks, and push its left pair and its right pair. A queue instead of a stack compares the trees level by level. Both check each pair once; they only swap the call stack for your own.

How does Same Tree help with Subtree of Another Tree?

Subtree of Another Tree runs this exact check starting from every node of the bigger tree, and answers true as soon as one starting node matches the smaller tree completely.