Blind 75 · Trees

Same Tree

Easy

Watch the walkthrough (5:21)

Problem

The input is p and q, the roots of two binary trees.
The trees are the same when they have the same shape, with the same value at every node.
Return true if they are the same, and false if they are not.
Two empty trees are the same.

Examples

Example 1:
Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:
Input: p = [1,2], q = [1,null,2]
Output: false
Explanation: same values, different shape — the 2 hangs on different sides.

Example 3:
Input: p = [1,2,1], q = [1,1,2]
Output: false

Example 4:
Input: p = [], q = []
Output: true

Constraints

0 <= number of nodes in each tree <= 100
-10^4 <= Node.val <= 10^4

Prerequisites

Binary trees, and recursion over them: solve the children, combine, return. The base case is almost always the empty tree.
Depth-first order (pre, in, post) and breadth-first by level — and knowing which one a problem is really asking for.

How to think about it

1. Walk Both in Lockstep Optimal

Intuition

Two trees are identical when their roots match and their corresponding subtrees are identical — the recursion mirrors the definition exactly. Putting the both-empty case first is what makes the rest short: after it, one being empty is an immediate no.

Algorithm

1. Both empty: identical.
2. Exactly one empty, or values differ: not identical.
3. Otherwise both left subtrees and both right subtrees must be identical.

Time & Space

Time O(min(n, m)) — the walk stops at the first difference. Space O(h).

2. Empty or Different, One Check

Intuition

The same walk, with the two checks that answer false joined in one if: one tree empty, or the two values different. Either way the pair is not the same, so one return serves both. Kept apart, as the first approach keeps them, each check is a line of its own, which is easier to follow in a walkthrough and to stop on in a debugger; the work is the same.

Algorithm

1. Both empty: identical.
2. Exactly one empty, or values differ: not identical.
3. Otherwise both left subtrees and both right subtrees must be identical.

Time & Space

Time O(min(n, m)) — the walk stops at the first difference. Space O(h).