Skip to content
Decoder

Subtree of Another Tree

Easy

Problem

You are given two binary trees, root and subRoot. Return True if some node in root, together with all of its descendants, forms a tree with exactly the same structure and values as subRoot. Otherwise return False.

The whole of root counts as one of its own subtrees.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
root = [3, 4, 5, 1, 2], subRoot = [4, 1, 2]
Output
True

Example 2

Input
root = [3, 4, 5, 1, 2, null, null, null, null, 0], subRoot = [4, 1, 2]
Output
False
Why
the 2 has an extra child

Example 3

Input
root = [1, 1], subRoot = [1]
Output
True

Constraints

  • 1 <= number of nodes in root <= 2000
  • 1 <= number of nodes in subRoot <= 1000
  • -10^4 <= Node.val <= 10^4

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.