InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Same Tree

easy Original ↗ 00:00

Problem

Given the roots of two binary trees p and q, decide whether the two trees are identical: they must have exactly the same shape, and every corresponding pair of nodes must hold the same value. Return True if they are identical, False otherwise.

Examples

Example 1

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

Both trees are a root 1 with left child 2 and right child 3 — same structure, same values.

Example 2

Input: p = [1,2], q = [1,null,2]
Output: False

Both trees contain the values {1, 2}, but p’s 2 is a left child while q’s 2 is a right child — the shapes differ.

Example 3

Input: p = [1,2,1], q = [1,1,2]
Output: False

Same shape, but the children’s values are swapped: 2 vs 1 on the left, 1 vs 2 on the right.

Constraints

  • The number of nodes in each tree is in the range [0, 100].
  • -10^4 <= Node.val <= 10^4

The bounds are small, so any O(n) traversal is fine. The challenge is the structural comparison, not speed.

Think about it first

Hint 1 When are two trees the same? Think about what must hold at the roots, and what must hold for the subtrees.
Hint 2 There are three cases for the pair (p, q): both are None, exactly one is None, or both exist. Only the last case needs further work.
Hint 3 Two trees are the same iff both roots are None, or both exist with equal values AND their left subtrees are the same AND their right subtrees are the same. That sentence is the recursion.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug