Subtree of Another Tree

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
Main Tree34512Target Subtree412Comparing...Matching Process1Check node 4 as potential root2Compare structure recursively3Match found - return true!The highlighted nodes show the matching subtree pattern
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)

n
2n
โœ“ Linear Growth
Space Complexity
O(max(m, n))

Recursion stack depth is at most the height of the larger tree

n
2n
โšก Linearithmic Space

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 <= Node.val <= 104
  • Both trees are guaranteed to be valid binary trees
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
52.3K Views
High Frequency
~18 min Avg. Time
1.8K 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