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 INPUT Main Tree (root) 3 4 5 1 2 SubTree (subRoot) 4 1 2 root=[3,4,5,1,2] subRoot=[4,1,2] ALGORITHM STEPS 1 Serialize Main Tree Convert to string: "#3#4#1##2###5##" 2 Serialize SubTree Convert to string: "#4#1##2##" 3 Check Substring Is subTree string in main string? 4 Return Result Contains() returns true/false Serialization Format Pre-order: #node#left#right null marked as "#" "#3#4#1##2###5##".contains("#4#1##2##") Substring found at position 2! FINAL RESULT Match Found! 4 1 2 = subRoot true Subtree exists! Node 4 in root has identical structure Key Insight: By serializing trees into strings using pre-order traversal with unique delimiters (#), we convert the subtree problem into a substring matching problem. If the serialized subRoot is a substring of serialized root, then subRoot is a subtree. Time: O(m*n) | Space: O(m+n) for string storage. TutorialsPoint - Subtree of Another Tree | String Serialization Approach
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