CodingNodes / Trees / Subtree of Another Tree System design Space play · ←→ step · R restart

Problem

You get the roots of two binary trees, root and subRoot. Return true if some node of root has a subtree that is identical to subRoot: same shape, same values, and covering everything below that node. The whole of root counts as a subtree of itself.

Both trees are given in level order, with null for a missing child.

Constraints

  • 1 ≤ number of nodes in root ≤ 2000
  • 1 ≤ number of nodes in subRoot ≤ 1000
  • -10000 ≤ Node.val ≤ 10000

Examples: pick one to animate

Solutions

TimeO(m · n) SpaceO(h)

Time: There are m nodes in the big tree. Each one may start a comparison that costs up to n steps, the size of the small tree.

Space: The recursion is as deep as the big tree is tall, plus the comparison, which is no deeper than the small tree.

Treat every node of the big tree as a possible starting point. At each one, run the same-tree check against the small tree. If it matches, return true. If not, look for the small tree in the left subtree, then in the right subtree. Most comparisons stop at the first mismatch, so they are cheap.