Same Tree

easy

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.

Hints

Two trees are the same when their roots are equal and both subtrees are pairwise the same.
Handle the null cases first: two nulls match, one null against a node does not.
Recurse on both trees at once, ANDing the left and right results.

Common doubts

If you read p.val when p is null you'll crash; the null checks must come first.
Both subtrees must match for the trees to be identical; OR would accept a mismatch on one side.
Yes — both null is the matching base case, returning true.

Interview follow-ups

Run this same-tree check at every node of the larger tree (LeetCode 572), or compare serialized forms.
Compare p.left with q.right and p.right with q.left instead — that's the symmetric-tree pattern.

Fun facts

  • Same-tree is the building block of subtree-of-another-tree: you just run it at every candidate root.
  • Swapping the recursion to cross the children (left-vs-right) turns this into the symmetric-tree check.

Asked at

AmazonMicrosoftApple
Frequently Sometimes Occasionally
Example 1
Input: p = [1, 2, 3], q = [1, 2, 3]
Output: true
Same structure and same values at every position.
Example 2
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.
Example 3
Input: p = [1, 2, 1], q = [1, 1, 2]
Output: false
Same structure but the child values are swapped.
Constraints

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

Solve this problem →