1. Double Recursive DFS (Traversal + Equality)
OptimalTraverse every candidate node in root with DFS. At each node, check if the subtree rooted there is strictly identical (isSameTree) to subRoot in structure and node values.
Where N is the number of nodes in root and M is the number of nodes in subRoot. In the worst case (e.g. repeated identical values), isSameTree is called for every node in root.
Consumes memory on the call stack proportional to the height H of root (at most O(n) for a skewed tree, O(log n) for a balanced tree).
How It Works
The Two-Level Recursive Strategy
This problem requires two distinct recursive functions working in tandem:
- Helper Function: `isSameTree(s, t)`:
- Compares if two trees are completely isomorphic (identical structure and values):
- If both
s == nullandt == null, returntrue(both empty). - If only one is null, or if
s.val != t.val, returnfalse. - Recurse:
isSameTree(s.left, t.left) && isSameTree(s.right, t.right).
- Main Function: `isSubtree(root, subRoot)`:
- If
subRoot == null, an empty tree is trivially a subtree of any tree; returntrue. - If
root == null, an empty main tree cannot contain a non-empty subRoot; returnfalse. - If
isSameTree(root, subRoot)istrue, we found a match! Returntrue. - Otherwise, check if
subRootmatches anywhere in the left subtree OR right subtree:isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot).
Strict Subtree Invariant: No Stray Descendants
A common mistake is returning true if subRoot is a subset of root. The definition requires the subtree to include all of the candidate node's descendants. The isSameTree equality check ensures that if subRoot has null children, the matched candidate must also have null children at those exact positions.
Step-by-Step Dry Run
Compare tree at 3 with subRoot (4). 3 != 4 -> isSameTree fails. Recurse into children of 3.
isSubtree(3.left, subRoot) || isSubtree(3.right, subRoot)- +Clean modular recursion pattern
- +Zero extra serialized string allocation
- -Worst-case O(n * m) time on trees with many duplicate node values
Reference Implementation
Complete implementation for Double Recursive DFS (Traversal + Equality) in Python, JavaScript, Java, C++, and C.
class TreeNode:def __init__(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = rightdef is_same_tree(s: TreeNode | None, t: TreeNode | None) -> bool:if not s and not t:return Trueif not s or not t or s.val != t.val:return Falsereturn is_same_tree(s.left, t.left) and is_same_tree(s.right, t.right)def is_subtree(root: TreeNode | None, sub_root: TreeNode | None) -> bool:if not sub_root:return Trueif not root:return Falseif is_same_tree(root, sub_root):return Truereturn is_subtree(root.left, sub_root) or is_subtree(root.right, sub_root)if __name__ == "__main__":# root: [3, 4, 5, 1, 2]root = TreeNode(3)root.left = TreeNode(4, TreeNode(1), TreeNode(2))root.right = TreeNode(5)# subRoot: [4, 1, 2]sub_root = TreeNode(4, TreeNode(1), TreeNode(2))print("Is Subtree:", is_subtree(root, sub_root))
function TreeNode(val, left, right) {
this.val = (val === undefined ? 0 : val);
this.left = (left === undefined ? null : left);
this.right = (right === undefined ? null : right);
}
function isSameTree(s, t) {
if (!s && !t) return true;
if (!s || !t || s.val !== t.val) return false;
return isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
}
function isSubtree(root, subRoot) {
if (!subRoot) return true;
if (!root) return false;
if (isSameTree(root, subRoot)) return true;
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}
const root = new TreeNode(3);
root.left = new TreeNode(4, new TreeNode(1), new TreeNode(2));
root.right = new TreeNode(5);
const subRoot = new TreeNode(4, new TreeNode(1), new TreeNode(2));
console.log("Is Subtree:", isSubtree(root, subRoot));public class Solution {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static boolean isSameTree(TreeNode s, TreeNode t) {
if (s == null && t == null) return true;
if (s == null || t == null || s.val != t.val) return false;
return isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
}
public static boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (subRoot == null) return true;
if (root == null) return false;
if (isSameTree(root, subRoot)) return true;
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(4, new TreeNode(1), new TreeNode(2));
root.right = new TreeNode(5);
TreeNode subRoot = new TreeNode(4, new TreeNode(1), new TreeNode(2));
System.out.println("Is Subtree: " + isSubtree(root, subRoot));
}
}#include <iostream>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* l, TreeNode* r) : val(x), left(l), right(r) {}
};
bool isSameTree(TreeNode* s, TreeNode* t) {
if (!s && !t) return true;
if (!s || !t || s->val != t->val) return false;
return isSameTree(s->left, t->left) && isSameTree(s->right, t->right);
}
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
if (!subRoot) return true;
if (!root) return false;
if (isSameTree(root, subRoot)) return true;
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
int main() {
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(4, new TreeNode(1), new TreeNode(2));
root->right = new TreeNode(5);
TreeNode* subRoot = new TreeNode(4, new TreeNode(1), new TreeNode(2));
std::cout << std::boolalpha << "Is Subtree: " << isSubtree(root, subRoot) << "\n";
return 0;
}#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
bool isSameTree(struct TreeNode* s, struct TreeNode* t) {
if (!s && !t) return true;
if (!s || !t || s->val != t->val) return false;
return isSameTree(s->left, t->left) && isSameTree(s->right, t->right);
}
bool isSubtree(struct TreeNode* root, struct TreeNode* subRoot) {
if (!subRoot) return true;
if (!root) return false;
if (isSameTree(root, subRoot)) return true;
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
int main(void) {
struct TreeNode* root = createNode(3);
root->left = createNode(4);
root->left->left = createNode(1);
root->left->right = createNode(2);
root->right = createNode(5);
struct TreeNode* subRoot = createNode(4);
subRoot->left = createNode(1);
subRoot->right = createNode(2);
printf("Is Subtree: %s\n", isSubtree(root, subRoot) ? "true" : "false");
return 0;
}