Skip to content
Onsite

Subtree of Another Tree

EasyP2Coding

Given the roots of two binary trees root and subRoot, return true if some node of root has a subtree that is identical to subRoot in structure and values. The subtree of a node is that node plus all of its descendants, down to the leaves.

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 node 4 has an extra descendant 0 under 2, so its subtree differs.

Constraints

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

Hints

Run checks the 3 visible tests, Submit all 9.