Subtree of Another Tree solution explained
To decide whether one binary tree is a subtree of another, visit every node of the larger tree and run an exact same-tree comparison against the smaller tree from that node. That expected answer costs O(m × n) in the worst case. For a linear bound, serialize both trees in preorder with markers for missing children and check whether the small tree's sequence appears inside the big tree's with a string-matching algorithm such as KMP.
By Evin JohnPublished 8 min read
The question, in plain terms
You get two binary trees, a big one and a small one. Return true if the big tree contains a node such that the subtree rooted there, meaning that node and all of its descendants, is identical in shape and values to the small tree. The big tree counts as a subtree of itself.
big: 7
/ \
8 9
/ \
5 1
8 with children 5 and 1 -> true (the left subtree, exactly)
8 with only child 5 -> false (big's 8 also has the child 1)
9 alone -> true (a leaf is a subtree)
7 with children 8 and 9 -> false (big's 8 has children this one lacks)The second and fourth candidates are the important ones. Each matches the top of something in the big tree, but a subtree includes all descendants, so a node in the big tree with extra children below cannot match. Ask whether an empty small tree should count as a subtree; it usually does, but the case rarely comes up.
What it tests
This problem checks whether you can compose two tree traversals: one that searches every node and one that compares two trees. Interviewers expect the O(m × n) answer and are happy with it if your helper is correct. The serialization idea is a strong follow-up that shows you can turn a tree problem into a string problem. Make sure your comparison helper is solid first; it is the Same Tree check.
The expected answer: compare from every node
Write a matches helper that walks two trees in lockstep and returns true only if they are identical. Then walk the big tree. At each node, try matches(node, small). If it fails, try both children. Short-circuit evaluation stops the search at the first success.
def matches(a, b):
if a is None or b is None:
return a is b
return a.val == b.val and matches(a.left, b.left) and matches(a.right, b.right)
def has_subtree(big, small):
if big is None:
return small is None
return (matches(big, small)
or has_subtree(big.left, small)
or has_subtree(big.right, small))function matches(a, b) {
if (a === null || b === null) return a === b;
return a.val === b.val && matches(a.left, b.left) && matches(a.right, b.right);
}
function hasSubtree(big, small) {
if (big === null) return small === null;
return matches(big, small) || hasSubtree(big.left, small) || hasSubtree(big.right, small);
}The worst case appears when many nodes share the small tree's root value and nearly match. For example, a big tree that is a long chain of identical values and a small tree that is a slightly shorter chain ending in a different value forces almost a full comparison at every node. On typical trees, most comparisons fail on the first value, so the search is much faster than the bound suggests.
Linear time: serialize, then search
A preorder listing of values that also records every missing child uniquely describes a tree. Better still, the listing of any subtree appears as a contiguous run inside the listing of the whole tree, because preorder writes a node and then everything under it before moving on. So the small tree is a subtree exactly when its listing appears as a run inside the big tree's listing. That is substring search, and the Knuth-Morris-Pratt algorithm does it in O(m + n).
def tokens(node, out):
# preorder with an explicit marker for every missing child
if node is None:
out.append(None)
else:
out.append(node.val)
tokens(node.left, out)
tokens(node.right, out)
return out
def contains_run(text, pattern):
# Knuth-Morris-Pratt over lists: is pattern a contiguous run inside text?
fail = [0] * len(pattern)
k = 0
for i in range(1, len(pattern)):
while k and pattern[i] != pattern[k]:
k = fail[k - 1]
if pattern[i] == pattern[k]:
k += 1
fail[i] = k
k = 0
for item in text:
while k and item != pattern[k]:
k = fail[k - 1]
if item == pattern[k]:
k += 1
if k == len(pattern):
return True
return False
def has_subtree_linear(big, small):
return contains_run(tokens(big, []), tokens(small, []))function tokens(node, out) {
if (node === null) {
out.push(null);
} else {
out.push(node.val);
tokens(node.left, out);
tokens(node.right, out);
}
return out;
}
function containsRun(text, pattern) {
const fail = new Array(pattern.length).fill(0);
for (let i = 1, k = 0; i < pattern.length; i++) {
while (k > 0 && pattern[i] !== pattern[k]) k = fail[k - 1];
if (pattern[i] === pattern[k]) k++;
fail[i] = k;
}
for (let i = 0, k = 0; i < text.length; i++) {
while (k > 0 && text[i] !== pattern[k]) k = fail[k - 1];
if (text[i] === pattern[k]) k++;
if (k === pattern.length) return true;
}
return false;
}
function hasSubtreeLinear(big, small) {
return containsRun(tokens(big, []), tokens(small, []));
}Matching on lists of tokens rather than one joined string avoids a classic bug. If you join values into a string, the value 2 inside the small tree can match the end of 12 in the big tree. With strings you must add a separator before every value, for example writing ,2 and ,12. Token lists side-step the issue entirely. You could also hash each subtree bottom-up and compare hashes, which is linear on average but needs a check for collisions.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Same-tree check from every node | O(m × n) worst case | O(height) recursion |
| Serialize both, built-in substring search | Depends on the library's search; often fast in practice | O(m + n) |
| Serialize both, KMP | O(m + n) | O(m + n) |
| Hash every subtree | O(m + n) on average | O(m + n) |
Inputs to test
- The small tree equals the whole big tree.
- The small tree is a single leaf that exists in the big tree.
- A top-part match with extra descendants in the big tree, like the second candidate.
- Values that are prefixes or suffixes of each other, such as 2 and 12, to catch string-joining bugs.
- Repeated values, so several nodes look like candidate roots.
Common pitfalls
- Comparing only values along the way and forgetting that shapes must match too.
- Returning true when the small tree matches the top of a node whose children continue further down.
- Serializing without gap markers, which loses the shape.
- Joining values into a string with no separators, which lets 2 match the tail of 12.
- Using in-order serialization. Even with gap markers, different trees can share an in-order listing, such as a 1 with a left child 1 and a 1 with a right child 1. Preorder or postorder with markers is the safe choice.
Follow-ups
- Count how many times the small tree appears. With KMP, keep going after a match instead of returning.
- Find all duplicate subtrees in one tree. Serialize every subtree bottom-up and count the encodings in a hash map.
- Allow the match to stop early, ignoring descendants. That is a different question: compare only while the small tree has nodes.
- Very large trees on disk. Hash subtrees bottom-up and compare compact hashes instead of full structures.
Explaining it
Fictional example
- Candidate
- I need a node in the big tree whose whole subtree equals the small one. I'll reuse a same-tree helper and try it from every node, which is O(m times n) in the worst case.
- Candidate
- If that's too slow, preorder with null markers gives each subtree a contiguous run in the listing, so I can search for the small tree's run with KMP in linear time.
- Candidate
- I'll keep tokens in lists rather than one string, so a 2 can't match the end of a 12.
Related problems
Same Tree is the helper this problem relies on. Validate Binary Search Tree and Diameter of Binary Tree are other checks that must look at every node, and the coding problems hub lists the rest.
Rehearsing with Natively
Natively runs on Mac and Windows and can read two tree drawings from a screenshot while you practice, then explain the gap between a top-part match and a true subtree, or how preorder with markers turns this into substring search. It also transcribes the mock so you can review your explanation of the worst case. See the AI interview assistant.
Questions people ask
How do you solve Subtree of Another Tree?
Visit every node of the big tree and run a same-tree comparison against the small tree from there. Return true on the first exact match, including all descendants. This is O(m times n) in the worst case.
Can Subtree of Another Tree be solved in linear time?
Yes. Serialize both trees in preorder with a marker for every missing child. The small tree is a subtree exactly when its sequence appears as a contiguous run in the big tree's sequence, which KMP finds in O(m + n).
Why does the serialization need markers for missing children?
Without them, trees with different shapes can produce the same list of values, so a match in the listing would not prove the shapes match.
What is the difference between a subtree and a matching top part?
A subtree includes every descendant of its root. If the big tree's node has extra children below where the small tree ends, it is not a match.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
