Subtree of Another Tree - Problem
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 of 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. The tree tree could also be considered as a subtree of itself.
Input & Output
Example 1 — Basic Subtree 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 same structure and values as subRoot: both have 4 as root with left child 1 and right child 2
Example 2 — No Match Found
$
Input:
root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
›
Output:
false
💡 Note:
Although node 4 exists in main tree, the subtree rooted at 4 has an additional node 0 under node 2, so it doesn't exactly match subRoot
Example 3 — Entire Tree Match
$
Input:
root = [1,2,3], subRoot = [1,2,3]
›
Output:
true
💡 Note:
The entire main tree matches the subRoot exactly - a tree is considered a subtree of itself
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 ≤ root.val ≤ 104
- -104 ≤ subRoot.val ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Trees
Main tree [3,4,5,1,2] and target subtree [4,1,2]
2
Search Process
Check each node in main tree as potential subtree root
3
Match Found
Subtree rooted at node 4 matches target exactly
Key Takeaway
🎯 Key Insight: A subtree match requires identical structure AND node values at every corresponding position
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code