Home
DSA Patterns
Depth-First Search
Subtree of Another Tree
Subtree of Another Tree (LeetCode 572)
Subtree of Another Tree (LeetCode 572): check whether one binary tree appears as an exact subtree of another by running the Same Tree check from every node.
Problem Understanding
Subtree of Another Tree: given the roots of two binary trees root and subRoot, return true if some node of root has a subtree with exactly the same structure and values as subRoot. A subtree is a node together with all of its descendants.
Example: root = [3, 4, 5, 1, 2] and subRoot = [4, 1, 2] returns true: the tree under node 4 is [4, 1, 2].
The Intuition: Same Tree, From Every Node
The question breaks into two smaller ones:
- Where could the match start? Any node of
root. A DFS overrootvisits each one. - Does it match from here? That is exactly Same Tree: compare the tree at this node with
subRoot, node by node.
So at each node: run the Same Tree check; if it passes, return true; otherwise search the left subtree, then the right. Both checks stop at the first difference.
Subtree of Another Tree Visualization
OUTLINED: THE START BEING TRIED
TRY A START
root
subRoot
Trying
3
Rejected
0
Subtree?
:
isSubtree(3): could the match start at 3?
Next
Run the Same Tree check: the tree at 3 against subRoot
root
subRoot
root and subRoot are drawn side by side. The node of root being tried as a starting point is outlined; inside each Same Tree check, the pair being compared is marked in both trees and a difference turns red. Rejected starting points fade, and the matching subtree turns green.
Subtree of Another Tree Dry Run
Input: root = [3, 4, 5, 1, 2], subRoot = [4, 1, 2]
| Start | Same Tree check | Result |
|---|---|---|
| 3 | 3 ≠ 4 | not here, search left |
| 4 | 4 = 4, then 1 = 1, then 2 = 2, all children empty | match: return true |
The right subtree of 3 is never searched, because the left one already returned true.
A Faster Approach
The check above is O(m · n) in the worst case. To do better, serialize both trees in preorder with markers for empty children (so that shape is kept), then test whether the subRoot string occurs in the root string with a linear-time string search such as KMP: O(m + n). In interviews the recursive version is the expected first answer; the serialization idea is a common follow-up.
Subtree of Another Tree LeetCode Solution
DFS over root, calling the Same Tree check at each node.
Subtree of Another Tree Code
1var isSubtree = function(root, subRoot) {2 if (!root) {3 return false;4 }5 if (isSame(root, subRoot)) {6 return true;7 }8 return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);9};1011function isSame(p, q) {12 if (!p && !q) {13 return true;14 }15 if (!p || !q || p.val !== q.val) {16 return false;17 }18 return isSame(p.left, q.left) && isSame(p.right, q.right);19}
Subtree of Another Tree in Python, Java, C++, TypeScript and C
Subtree of Another Tree in Python
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
if not root:
return False
if self.isSame(root, subRoot):
return True
return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
def isSame(self, p, q):
if not p and not q:
return True
if not p or not q or p.val != q.val:
return False
return self.isSame(p.left, q.left) and self.isSame(p.right, q.right)Subtree of Another Tree in Java
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (root == null) {
return false;
}
if (isSame(root, subRoot)) {
return true;
}
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}
private boolean isSame(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null || p.val != q.val) {
return false;
}
return isSame(p.left, q.left) && isSame(p.right, q.right);
}
}Subtree of Another Tree in C++
class Solution {
public:
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
if (!root) {
return false;
}
if (isSame(root, subRoot)) {
return true;
}
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
private:
bool isSame(TreeNode* p, TreeNode* q) {
if (!p && !q) {
return true;
}
if (!p || !q || p->val != q->val) {
return false;
}
return isSame(p->left, q->left) && isSame(p->right, q->right);
}
};Subtree of Another Tree in TypeScript
function isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean {
if (!root) {
return false;
}
if (isSame(root, subRoot)) {
return true;
}
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}
function isSame(p: TreeNode | null, q: TreeNode | null): boolean {
if (!p && !q) {
return true;
}
if (!p || !q || p.val !== q.val) {
return false;
}
return isSame(p.left, q.left) && isSame(p.right, q.right);
}Subtree of Another Tree in C
bool isSame(struct TreeNode* p, struct TreeNode* q) {
if (!p && !q) {
return true;
}
if (!p || !q || p->val != q->val) {
return false;
}
return isSame(p->left, q->left) && isSame(p->right, q->right);
}
bool isSubtree(struct TreeNode* root, struct TreeNode* subRoot) {
if (!root) {
return false;
}
if (isSame(root, subRoot)) {
return true;
}
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}Edge Cases & Common Mistakes
- Extra descendants: a node whose values match
subRootbut which has more children below is not a match; the Same Tree check catches it at the extra node. - Matching values at the wrong node: the first node with value
4may fail while a later one matches, so the search must continue after a failed check. - Comparing only the root values: checking
root.val == subRoot.valis not enough; the whole subtree must be identical. - Single-node
subRoot: it matches any leaf with the same value, but not an internal node with that value.
Summary
Subtree of Another Tree is two DFS walks nested: an outer one that picks each node of root as a possible start, and the Same Tree check that compares from there. Both stop as soon as the answer is known.
More practice: DSA interview questions with answers · patterns cheat sheet
