Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Easy Trees / DFS High frequency Solution Available Practice Mode

Subtree of Another Tree LeetCode Solution

Tags: #Tree #Depth-First Search #String Matching #Binary Tree #Hash Function

Approach Summary

Traverse the main binary tree. At each node, evaluate whether the subtree rooted at that node is identical to the target subRoot using the Same Tree comparison.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Trees / DFS Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Trees / DFS pattern.

Framework: Trees / DFS • Interview Prep: Tested at FAANG • Explore all Trees / DFS problems & invariants →

How to Recognize This Pattern

  • Check if target tree is a subtree of main tree
  • Combine tree traversal with identical tree verification

Complexity Analysis

Time Complexity

O(m * n)

Space Complexity

O(h)

Tags

Tree Depth-First Search String Matching Binary Tree Hash Function

Frequently Asked Questions

What is the optimal time and space complexity for Subtree of Another Tree?
The optimal solution for Subtree of Another Tree achieves O(m * n) runtime complexity and requires O(h) auxiliary space. For each node in the main tree of size m, isSameTree takes up to O(n) comparisons. Hence worst-case time is O(m * n) (e.g. repeated values like long paths of 1s). Average time on realistic trees is O(m + n). Auxiliary space is O(h) for call stack depth.
How do I identify that Subtree of Another Tree requires the Trees / DFS pattern?
In technical interviews, look for key problem signals: Check if target tree is a subtree of main tree; Combine tree traversal with identical tree verification. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Trees / DFS strategy.
What critical edge cases must be handled in Subtree of Another Tree?
Essential edge cases to verify include: subRoot is identical to the entire tree root (returns true); Single leaf matching subRoot val but having extra children (returns false because full subtree must match); Target subRoot appears multiple times in root with different children; root is null (returns false). Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Subtree of Another Tree?
Subtree of Another Tree is a Easy-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Facebook, Microsoft.
Buy me a coffee
Daily Practice
0/0