Skip to content

Subtree of Another Tree

EasyTrees
Decode it first. Clues, constraints, pattern and plan before any code.

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.

root = [3, 4, 5, 1, 2],                                subRoot = [4, 1, 2]  →  True
root = [3, 4, 5, 1, 2, null, null, null, null, 0],     subRoot = [4, 1, 2]  →  False   (the 2 has an extra child)
root = [1, 1],                                         subRoot = [1]        →  True

Constraints

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