Task example: Same Tree

Compare two binary trees. Return True only if corresponding positions contain equal values and the same children. An empty position must be empty in both trees.

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

The values and their positions match.

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

The child is on different sides, so the shapes differ.

LeetCode 100 ↗
01 / Recursive DFS

Recursive DFS: video explanation

p = [1,2,3]
q = [1,2,3]
output: True

Prefer reading? Follow the steps below.

  1. Two empty subtrees match. If only one is empty, their shapes differ. If both exist, compare their values.
  2. Compare the left children, then the right children. Both comparisons must succeed; a failed left comparison skips the right one.
  3. Return True only when shape and values match throughout. Neither input tree is modified.

Time complexity · O(n)

For equal trees with n nodes each, every corresponding pair is checked once. A mismatch may stop the search early.

Space complexity · O(h)

Recursive calls use O(h) space, where h is the explored height: O(log n) for a balanced tree and O(n) for a skewed tree.

PYTHONLive code trace
02 / Iterative DFS

Iterative DFS: video explanation

p = [1,2,3]
q = [1,2,3]
output: True

Prefer reading? Follow the steps below.

  1. Put the two roots together on a stack. Pop one corresponding pair at a time.
  2. Skip two empty nodes. Stop with False for a missing counterpart or unequal values.
  3. Push the right pair, then the left pair. Return True after every pending pair has matched.

Both approaches have the same worst-case bounds. Iterative DFS avoids Python's recursion limit; it is not a constant-space solution.

Time complexity · O(n)

For equal trees with n nodes each, every corresponding pair is checked once. A mismatch may stop the search early.

Space complexity · O(h)

The stack holds O(h) pending pairs, including empty children. In the worst case it uses O(n) space.

PYTHONLive code trace

Same Tree · The task

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.