Subtree of Another Tree - Problem
Subtree of Another Tree
Given two binary trees
A subtree is defined as a tree consisting of any node in the original tree and all of its descendants. The tree itself can also be considered its own subtree.
Goal: Return
Example:
If
Given two binary trees
root and subRoot, determine if there exists a subtree within root that has the exact same structure and node values as subRoot.A subtree is defined as a tree consisting of any node in the original tree and all of its descendants. The tree itself can also be considered its own subtree.
Goal: Return
true if such a matching subtree exists, false otherwise.Example:
If
root is [3,4,5,1,2] and subRoot is [4,1,2], then subRoot appears as a subtree starting at node 4 in root, so return true. Input & Output
example_1.py โ Basic Match
$
Input:
root = [3,4,5,1,2], subRoot = [4,1,2]
โบ
Output:
true
๐ก Note:
The subtree rooted at node 4 in the main tree has the exact structure [4,1,2] matching subRoot
example_2.py โ No Match
$
Input:
root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
โบ
Output:
false
๐ก Note:
Although node 4 exists with children 1 and 2, node 2 has an additional child 0, so the structure doesn't match exactly
example_3.py โ Single Node Match
$
Input:
root = [1,2,3], subRoot = [2]
โบ
Output:
true
๐ก Note:
The single node 2 in the main tree matches the single-node subtree [2]
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Search
Start from the root of the main tree and prepare to check each node
2
Check Current Node
At each node, use helper function to compare subtree structure with target
3
Tree Comparison
Helper function recursively compares node values and structure
4
Continue or Return
If match found, return true; otherwise, recursively search left and right children
Key Takeaway
๐ฏ Key Insight: We need two separate recursive functions - one to traverse all possible starting points, and another to perform deep structural comparison between trees.
Time & Space Complexity
Time Complexity
O(m ร n)
In worst case, we check every node in main tree (m nodes) and for each, compare entire subtree (n nodes)
โ Linear Growth
Space Complexity
O(max(m, n))
Recursion stack depth is at most the height of the larger tree
โก Linearithmic Space
Constraints
-
The number of nodes in the
roottree is in the range [1, 2000] -
The number of nodes in the
subRoottree is in the range [1, 1000] - -104 <= Node.val <= 104
- Both trees are guaranteed to be valid binary trees
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code