Subtree of Another Tree
Problem Statement
You are given two binary trees, root and subRoot. Decide whether subRoot appears inside root: some node of root must have a subtree with exactly the same shape and the same values as subRoot.
A node together with all of its descendants is a subtree. The whole tree counts as a subtree of itself.
Two roots, root and subRoot. Both trees have at least one node.
true if some subtree of root matches subRoot exactly, false otherwise.
The node 4 with its two children 1 and 2 is exactly subRoot.
The node 4 has the same value and the same first two children, but the node 2 has an extra child 0. The subtree is not an exact match.
- • The number of nodes in root is in the range [1, 2000].
- • The number of nodes in subRoot is in the range [1, 1000].
- • −10^4 ≤ root.val ≤ 10^4
- • −10^4 ≤ subRoot.val ≤ 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Run Same Tree from every node of root against subRoot
Write both trees as preorder text with a comma before each token and # for empty children, then search with KMP
A matching subtree starts at some node of root. So try subRoot at each node: if Same Tree says yes at any node, the answer is yes. This is correct and accepted. It costs O(m · n) in the worst case, where m and n are the sizes of root and subRoot.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.