Skip to main content
CodeOath
← All problems

Problem

Subtree of Another Tree

Easy
  • trees

Decide whether subRoot can be found inside root. Pick any node of root and take it together with everything beneath it. If that piece looks exactly like subRoot, with the same shape and the same values, the answer is true. If no node gives a match, it is false.

The piece must be the node's whole subtree. A node with extra descendants below it does not match.

Trees in this problem are written as level-order arrays: the root first, then each level from left to right. null marks a missing child, and a missing child has no entries beneath it. Trailing nulls are omitted.

Example 1
Input
root = [10, 5, 12, 2, 7, null, 15], subRoot = [5, 2, 7]
Output
true
Explanation

the node 5 in root has children 2 and 7 and nothing below them, exactly like subRoot.

Example 2
Input
root = [10, 5, 12, 2, 7, null, 15, null, null, 6], subRoot = [5, 2, 7]
Output
false
Explanation

the node 5 still has children 2 and 7, but 7 now has a child 6, so the piece under 5 is bigger than subRoot.

Constraints:

  • root and subRoot each have at least one node

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.