Subtree of Another Tree (LeetCode 572): Solution and Explanation
You are given two binary trees, root and subRoot, and must decide whether subRoot appears inside root as a complete subtree. That means some node in root, together with all of its descendants, has exactly the same shape and values as subRoot.
Watch it run step by step
Try your own input and write the code →Intuition
A subtree is not just any matching chunk of nodes. If a node in root is chosen as the starting point, everything below it must match subRoot, down to the leaves. So the question reduces to two smaller ones: which node of root could be the starting point, and does the tree hanging from that node equal subRoot exactly?
The second question is the classic same-tree check: two trees are equal when their roots match and their left and right subtrees are recursively equal. The first question has no shortcut in general, because the match could start at any node. So the natural approach is to walk every node of root and run the same-tree check from there, stopping as soon as one succeeds.
This is brute force with good structure, and for the usual constraints (a few thousand nodes) it is fast enough, because most same-tree checks fail within a step or two when the root values differ. If you need guaranteed linear time, you can serialize both trees with null markers and run a string matching algorithm, but the nested recursion is what interviewers usually expect first.
Approach: DFS over root with a same-tree check at each node
- If
subRootis empty, return True, since an empty tree is a subtree of anything. - If
rootis empty butsubRootis not, return False because there is nowhere left to match. - Call
isSameTree(root, subRoot). If the tree rooted at the current node equalssubRoot, return True. - Otherwise recurse into
root.leftand thenroot.right, returning True if either side containssubRoot. - Inside
isSameTree, return True when both nodes are None, False when exactly one is None or the values differ, and otherwise require both the left pair and right pair to match.
Step-by-step example
root = [3,4,5,1,2], subRoot = [4,1,2]
- At the root node 3,
isSameTree(3, 4)fails immediately because 3 differs from 4. - Recurse into the left child, node 4. Now
isSameTree(4, 4)compares the roots, which match. - It compares the left children 1 and 1, which match and both have no children, then the right children 2 and 2, which also match.
- The same-tree check returns True, so
isSubtreeat node 4 returns True, and theorat node 3 returns True without exploring node 5. - If node 2 in
roothad an extra child 0, the check at node 4 would fail at that child, every other start would fail too, and the answer would be False.
Code: Python, Java, C++
1class Solution:
2 def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
3 if not subRoot: return True
4 if not root: return False
5
6 if self.isSameTree(root, subRoot):
7 return True
8
9 return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
10
11 def isSameTree(self, p, q):
12 if not p and not q: return True
13 if not p or not q or p.val != q.val: return False
14 return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)1class Solution {
2 public boolean isSubtree(TreeNode root, TreeNode subRoot) {
3 if (subRoot == null) return true;
4 if (root == null) return false;
5
6 if (isSameTree(root, subRoot)) return true;
7
8 return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
9 }
10
11 private boolean isSameTree(TreeNode p, TreeNode q) {
12 if (p == null && q == null) return true;
13 if (p == null || q == null || p.val != q.val) return false;
14 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
15 }
16}1class Solution {
2public:
3 bool isSubtree(TreeNode* root, TreeNode* subRoot) {
4 if (!subRoot) return true;
5 if (!root) return false;
6
7 if (isSameTree(root, subRoot)) return true;
8
9 return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
10 }
11
12 bool isSameTree(TreeNode* p, TreeNode* q) {
13 if (!p && !q) return true;
14 if (!p || !q || p->val != q->val) return false;
15 return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
16 }
17};Time and space complexity
O(m × n)
There are m nodes in root that can serve as a starting point, and each same-tree check may examine up to n nodes of subRoot before finishing. In practice most checks stop early on the first value mismatch.
O(h)
The recursion depth is bounded by the height of root plus the height of subRoot, so the stack uses space proportional to tree height rather than node count.
Other approaches
Serialize and string match (time O(m + n), space O(m + n))
Serialize both trees in preorder with explicit null markers and separators around each value, then check whether the subRoot string occurs in the root string using KMP or a similar linear matcher. The separators prevent a value like 2 from matching inside 12.
Merkle-style subtree hashing (time O(m + n), space O(m))
Compute a hash for every subtree bottom up from its value and its children's hashes, then look for a node whose hash equals the hash of subRoot, confirming with a same-tree check to rule out collisions.
Common mistakes
- Returning the result of
isSameTreeat the root directly instead of falling through to the children when it is False. - Treating a partial match as a subtree. The descendants of the matched node must line up all the way to the leaves, which is why a full same-tree check is required.
- Serializing without null markers or without delimiters, which lets different trees or different numbers produce false string matches.
- Mixing up the arguments and checking whether
rootis a subtree ofsubRootin the recursive calls.
Frequently asked questions
What is the time complexity of Subtree of Another Tree?
The straightforward recursive solution is O(m × n) in the worst case, where m and n are the node counts of the two trees. It runs a same-tree comparison from each node of the larger tree.
Can Subtree of Another Tree be solved in linear time?
Yes. Serialize both trees with null markers and delimiters, then use KMP or the Z algorithm to search for the smaller string inside the larger one. Subtree hashing is another linear-time option.
What is the difference between a subtree and a matching subgraph?
A subtree must include a node and every one of its descendants. You cannot stop partway down, so if the candidate node in root has an extra child that subRoot does not have, it is not a match.