Subtree of Another Tree

Check if one tree is a subtree of another.

Pattern

Tree Matching

This problem follows the Tree Matching pattern, commonly found in the Trees category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

At each node, check if it's identical to subRoot. Recurse on left and right.

Key Insight

Reuse the 'same tree' check at every node — it's O(m*n) but simple. For O(n), you can serialize both trees and use string matching.

Step-by-step

  1. 1If root is null, return false
  2. 2Check if the current subtree is identical to subRoot
  3. 3If not, recursively check the left and right subtrees

Pseudocode

def isSubtree(root, subRoot):
    if not root: return false
    if isSameTree(root, subRoot): return true
    return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)
Complexity Analysis

Time Complexity

O(m * n)

Space Complexity

O(h)
More Trees Problems

Master this pattern with YeetCode

Practice Subtree of Another Tree and similar Trees problems with flashcards. Build pattern recognition through active recall.

Practice this problem