Skip to content
Problem 100 · LeetCode 100(opens in a new tab)

Same Tree

EasyRecursion

Two binary trees are handed to you by their root nodes, p and q. Decide whether they are the same tree.

Two trees count as the same when they have exactly the same shape and every pair of nodes in matching positions holds the same value. Return true or false.

Example 1

Input:  p = [5, 1, 6], q = [5, 1, 7]
Output: false
Why:    the right children hold 6 and 7
2 more examples and the constraints

Example 2

Input:  p = [3, 8], q = [3, null, 8]
Output: false
Why:    8 hangs on the left in p, on the right in q

Example 3

Input:  p = [4, 7, 9], q = [4, 7, 9]
Output: true
Why:    same shape, same value in every spot

Constraints

  • Each tree has between 0 and 100 nodes
  • −10,000 ≤ each node value ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Write both trees out and compareO(n)
  2. Compare both trees togetherO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for two trees of 100 nodesVerdict
Write out and compareO(n)
Passes; builds two lists first
Compare togetherO(n)
Best; stops at the first difference

n = nodes in the smaller tree, h = its height.

Edge cases to test

  • Both trees empty. Two empty trees are the same: return true.
  • One tree empty. An empty tree and a single node 0 differ. Do not read .val before checking for null.
  • Same values, different shape. [3, 8] and [3, null, 8] hold the same numbers but are not the same tree.
  • Mirror images. [1, 2, 3] and [1, 3, 2] differ; left must be compared with left, not with right.

Common mistakes

  • Reading p.val before checking that both nodes exist, which crashes on an empty child.
  • Comparing only the values in order (an inorder list without gap markers), which calls different shapes equal.
  • Returning true as soon as the roots match, without checking both subtrees.

How to talk through it

  1. 1Clarify. Can either tree be empty? Does same mean same shape and same values, or only the same set of values?
  2. 2Name the three cases. Both empty, one empty or values differ, or recurse on both sides.
  3. 3Code the recursion. Put the null checks first so .val is never read on an empty node.
  4. 4State the cost. O(n) time, O(h) stack space; mention a queue of pairs if deep recursion is a worry.
  5. 5Test out loud. Run two empty trees, one empty tree, and a same-values-different-shape pair.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?