CodingNodes / Trees / Same Tree System design Space play · ←→ step · R restart

Problem

You get the roots of two binary trees, p and q. Return true if the trees are identical: they have exactly the same shape, and matching nodes hold the same value.

Each tree is given in level order, with null for a missing child.

Constraints

  • 0 ≤ number of nodes in each tree ≤ 100
  • -1000 ≤ Node.val ≤ 1000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(h)

Time: Each pair of nodes is compared at most once, so the work is at most the size of the smaller tree.

Space: The recursion goes as deep as the trees are tall, h. That is log n for balanced trees and n for a chain.

Walk both trees together. If both nodes are empty, they match. If only one is empty, or the values differ, the trees are different. Otherwise the trees are the same exactly when the left children match and the right children match. Stop at the first mismatch.