Subtree of Another Tree
Subtree of Another Tree is a easy trees & bst problem solved with the traversals pattern.
The best approach, serialize both trees, then kmp, runs in O(m + n) time and O(m + n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from compare at every node up.
Problem
You are given the roots of two binary trees, root and subRoot. Return true if some node of root is the top of a subtree that is identical to subRoot: the same shape and the same value in every position. Otherwise return false.
The subtree at a node is that node together with all of its descendants. So a node whose children match subRoot but which has extra nodes further down does not count. The whole of root is also one of its own subtrees.
Examples
Example 1
- Input
root = [5, 3, 8, 1, 4], subRoot = [3, 1, 4]- Output
true- Why
- The node 3 in root has children 1 and 4 and nothing below them, which is exactly subRoot.
Example 2
- Input
root = [5, 3, 8, 1, 4, null, null, null, null, 2], subRoot = [3, 1, 4]- Output
false- Why
- Node 3 still has children 1 and 4, but 4 now has a child 2. A subtree takes every descendant, so the subtree at 3 has four nodes and does not equal subRoot.
Example 3
- Input
root = [2, 2, null, 2], subRoot = [2, 2]- Output
true- Why
- Root is a chain of three 2s going left. The subtree at the middle node is a 2 with a left child 2, which matches subRoot. The subtree at the top has one node too many.
Constraints
roothas1to2000nodes.subRoothas1to1000nodes.-10^4 <= Node.val <= 10^4
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 57 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Compare at every node | O(m * n) | O(h) |
| Serialize both trees, then KMP | O(m + n) | O(m + n) |
1Compare at every node
O(m * n)Each of the m nodes of root can start a comparison that walks up to n nodes of subRoot.O(h)Only the recursion stack, as deep as the height of root.A copy of subRoot, if it exists, starts at some node of root. Visit every node of root and run the same-tree check from there; stop at the first success.
- If root is null, there is nowhere left to look: return false.
- If the tree at root is identical to subRoot, return true.
- Otherwise look in the left subtree, then in the right subtree.
- isSame(a, b): if either is null, they are equal only if both are; else the values must match and both pairs of children must be the same.
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 a, TreeNode b) {
if (a == null || b == null) return a == b;
return a.val == b.val && isSame(a.left, b.left) && isSame(a.right, b.right);
}
}class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
if root is None:
return False
if self.isSame(root, subRoot):
return True
return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
def isSame(self, a: Optional[TreeNode], b: Optional[TreeNode]) -> bool:
if a is None or b is None:
return a is b
return a.val == b.val and self.isSame(a.left, b.left) and self.isSame(a.right, b.right)class Solution {
public:
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
if (root == nullptr) return false;
if (isSame(root, subRoot)) return true;
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
private:
bool isSame(TreeNode* a, TreeNode* b) {
if (a == nullptr || b == nullptr) return a == b;
return a->val == b->val && isSame(a->left, b->left) && isSame(a->right, b->right);
}
};function isSubtree(root, subRoot) {
if (root === null) return false;
if (isSame(root, subRoot)) return true;
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
}
function isSame(a, b) {
if (a === null || b === null) return a === b;
return a.val === b.val && isSame(a.left, b.left) && isSame(a.right, b.right);
}2Serialize both trees, then KMP
O(m + n)Serializing visits each node once, and KMP never moves backwards in the text, so both phases are linear in the sequence lengths (2m + 1 and 2n + 1 tokens).O(m + n)The two token sequences and the failure table, plus the recursion stack while serializing.Write each tree as its preorder sequence of values, with a special NULL token for every missing child. These sequences describe a tree exactly, and the sequence of any subtree of root is a contiguous block of root's sequence. So subRoot is a subtree exactly when its sequence appears inside root's sequence, which KMP finds in linear time. Working with whole tokens, not characters, keeps 2 from matching inside 12.
- Serialize: at null, append NULL; otherwise append the value, then serialize the left child, then the right child.
- Build the KMP failure table of the pattern (subRoot's sequence): fail[i] is the length of the longest proper prefix of pat[0..i] that is also a suffix of it.
- Scan the text (root's sequence) with a matched length k: while the next token differs and k > 0, fall back to fail[k - 1]; if it matches, k++.
- If k reaches the pattern length, return true. If the scan ends first, return false.
class Solution {
private static final int NULL = Integer.MIN_VALUE;
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
List<Integer> text = new ArrayList<>(), pat = new ArrayList<>();
serialize(root, text);
serialize(subRoot, pat);
int m = pat.size();
int[] fail = new int[m];
for (int i = 1, k = 0; i < m; i++) {
while (k > 0 && !pat.get(i).equals(pat.get(k))) k = fail[k - 1];
if (pat.get(i).equals(pat.get(k))) k++;
fail[i] = k;
}
for (int i = 0, k = 0; i < text.size(); i++) {
while (k > 0 && !text.get(i).equals(pat.get(k))) k = fail[k - 1];
if (text.get(i).equals(pat.get(k))) k++;
if (k == m) return true;
}
return false;
}
private void serialize(TreeNode node, List<Integer> out) {
if (node == null) {
out.add(NULL);
return;
}
out.add(node.val);
serialize(node.left, out);
serialize(node.right, out);
}
}class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
text: List[Optional[int]] = []
pat: List[Optional[int]] = []
self.serialize(root, text)
self.serialize(subRoot, pat)
m = len(pat)
fail = [0] * m
k = 0
for i in range(1, m):
while k > 0 and pat[i] != pat[k]:
k = fail[k - 1]
if pat[i] == pat[k]:
k += 1
fail[i] = k
k = 0
for t in text:
while k > 0 and t != pat[k]:
k = fail[k - 1]
if t == pat[k]:
k += 1
if k == m:
return True
return False
def serialize(self, node: Optional[TreeNode], out: List[Optional[int]]) -> None:
if node is None:
out.append(None)
return
out.append(node.val)
self.serialize(node.left, out)
self.serialize(node.right, out)class Solution {
public:
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
vector<int> text, pat;
serialize(root, text);
serialize(subRoot, pat);
int m = (int)pat.size();
vector<int> fail(m, 0);
for (int i = 1, k = 0; i < m; i++) {
while (k > 0 && pat[i] != pat[k]) k = fail[k - 1];
if (pat[i] == pat[k]) k++;
fail[i] = k;
}
for (int i = 0, k = 0; i < (int)text.size(); i++) {
while (k > 0 && text[i] != pat[k]) k = fail[k - 1];
if (text[i] == pat[k]) k++;
if (k == m) return true;
}
return false;
}
private:
static constexpr int NULL_TOKEN = INT_MIN;
void serialize(TreeNode* node, vector<int>& out) {
if (node == nullptr) {
out.push_back(NULL_TOKEN);
return;
}
out.push_back(node->val);
serialize(node->left, out);
serialize(node->right, out);
}
};function isSubtree(root, subRoot) {
const text = [], pat = [];
serialize(root, text);
serialize(subRoot, pat);
const m = pat.length;
const fail = new Array(m).fill(0);
for (let i = 1, k = 0; i < m; i++) {
while (k > 0 && pat[i] !== pat[k]) k = fail[k - 1];
if (pat[i] === pat[k]) k++;
fail[i] = k;
}
for (let i = 0, k = 0; i < text.length; i++) {
while (k > 0 && text[i] !== pat[k]) k = fail[k - 1];
if (text[i] === pat[k]) k++;
if (k === m) return true;
}
return false;
}
function serialize(node, out) {
if (node === null) {
out.push(null);
return;
}
out.push(node.val);
serialize(node.left, out);
serialize(node.right, out);
}Edge cases to test
- subRoot equals the whole of root
- subRoot is a single node that matches a leaf
- A node matches subRoot at the top but has an extra descendant further down
- Same values but a left child where subRoot has a right child
- Many nodes share subRoot's root value, so a match is only found deep in the tree
- Values whose digits overlap, like 2 and 12 (a string-based method must keep tokens apart)
Hints
Hint 1
You already know how to check whether two trees are identical. Where in root could a copy of subRoot start?
Hint 2
Trying every node of root as the start works, but can cost one full comparison per node. Can you turn each tree into a sequence so that a subtree becomes a contiguous block?
Hint 3
A preorder listing that also writes a marker for every missing child describes a tree exactly, and the listing of any subtree is a contiguous piece of the whole listing. Now it is a pattern search: use KMP.
FAQ
What is the best time complexity for Subtree of Another Tree?
Serialize both trees, then KMP runs in O(m + n) time and O(m + n) extra space. Serializing visits each node once, and KMP never moves backwards in the text, so both phases are linear in the sequence lengths (2m + 1 and 2n + 1 tokens).
Which pattern does Subtree of Another Tree use?
It is a trees & bst problem that uses the traversals pattern. Other problems with the same pattern: Binary Tree Level Order Traversal, Binary Tree Zigzag Level Order Traversal, Binary Tree Level Order Traversal II.
Is there a brute force solution for Subtree of Another Tree?
Yes. Compare at every node takes O(m * n) time and O(h) space. A copy of subRoot, if it exists, starts at some node of root.
Which edge cases should I test for Subtree of Another Tree?
subRoot equals the whole of root; subRoot is a single node that matches a leaf; A node matches subRoot at the top but has an extra descendant further down; Same values but a left child where subRoot has a right child; Many nodes share subRoot's root value, so a match is only found deep in the tree; Values whose digits overlap, like 2 and 12 (a string-based method must keep tokens apart).