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 root tree is in the range [1, 2000]
  • The number of nodes in the subRoot tree is in the range [1, 1000]
  • -104 ≤ root.val ≤ 104
  • -104 ≤ subRoot.val ≤ 104

Visualization

Tap to expand
Subtree of Another Tree - Problem OverviewMain Tree:34512Target Subtree:412Match?✓ Step 1: Check node 3 as root → No match (different structure)✓ Step 2: Check node 4 as root → Perfect match found!The subtree rooted at node 4 has identical structure and valuesResult: true
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
Asked in
Facebook 15 Amazon 12 Microsoft 8 Google 6
189.0K Views
Medium Frequency
~15 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen