Practice Problem
Subtree of Another Tree
Difficulty: Easy
Given the roots of two binary trees, determine if the second tree is a subtree of the first tree.
Subtree of Another Tree
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values as subRoot, and false otherwise.
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants.
Examples
Example 1:
Input: root = [3, 4, 5, 1, 2], subRoot = [4, 1, 2]
Output: true
3
/ \
4 5 4
/ \ / \
1 2 1 2Example 2:
Input: root = [3, 4, 5, 1, 2, null, null, null, null, 0], subRoot = [4, 1, 2]
Output: false
3
/ \
4 5 4
/ \ / \
1 2 1 2
/
0Constraints
- The number of nodes in
rootis in the range[1, 2000]. - The number of nodes in
subRootis in the range[1, 1000]. -10^4 <= Node.val <= 10^4
Expected Complexity
- Time: O(m * n) where m and n are sizes of the two trees
- Space: O(h) where h is the height of the root tree
EASY
Binary Tree
DFS
Recursion
Subtree Problems
Beginner
0 views
Solution
Hints
Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium
This section is available for CodeSnatch Premium members only.
