Blind 75
Subtree of Another Tree (easy)
Problem Statement
Given two binary trees s
and t
, determine if tree t
is a subtree of tree s
. A tree t
is considered a subtree of s
if there exists a node in s
such that the subtree of that node is identical to t
. Both trees are considered identical if their structure and nodes are the same.
Examples
-
- Input:
- Tree
s
: [3,4,5,1,2] - Tree
t
: [4,1,2]
- Tree
- Expected Output: true
- Justification: Tree
t
can be found as a subtree ofs
rooted at the node with value 4.
- Input:
-
- Input:
- Tree
s
: [1,2,3] - Tree
t
: [2,3]
- Tree
- Expected Output: false
- Justification: There's no subtree in
s
that looks like treet
.
- Input:
-
- Input:
- Tree
s
: [3,4,5,1,2,null,null,null,null,0] - Tree
t
: [4,1,2]
- Tree
- Expected Output: false
- Justification: Even though there's a subtree with root 4, it's not identical to tree
t
.
- Input:
Constraints:
- The number of nodes in the root tree is in the range [1, 2000].
- The number of nodes in the subRoot tree is in the range [1, 1000].
- -10<sup>4</sup> <= root.val <= 10<sup>4</sup>
- -10<sup>4</sup> <= subRoot.val <= 10<sup>4</sup>
Try it yourself
Try solving this question here:
Python3
Python3