Subtree of Another Tree
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given the roots of two binary trees root and subRoot, return true if root contains a subtree that is exactly subRoot, and false otherwise.
Understand the problem
- A subtree of
rootis any node inroottogether with everything below it (all its descendants). - You're asking: is there a node in
rootwhere, if you "cut out" that node and everything under it, you get a tree identical tosubRoot? (Identical means same shape and same values, as in Same Tree.) - All descendants count: a matching top part isn't enough if the node in
roothas extra children below.
Example 1
Input: root = [3, 4, 5, 1, 2], subRoot = [4, 1, 2]
Output: true
root: 3 subRoot: 4
/ \ / \
4 5 1 2
/ \
1 2The 4 in root, with its children 1 and 2, is exactly subRoot.
Example 2
Input: root = [3, 4, 5, 1, 2, null, null, null, null, 0], subRoot = [4, 1, 2]
Output: false
root: 3
/ \
4 5
/ \
1 2
/
0The 4 looks right at first, but its 2 has an extra child 0. The cut-out subtree is 4, 1, 2, 0, which isn't the same as subRoot.
How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child.
Constraints
1 <= number of nodes in root <= 20001 <= number of nodes in subRoot <= 1000
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Visit every node of the big tree, and at each one run the Same Tree check against subRoot.
The key insight
If subRoot appears inside root, it has to start at some node of root. So the problem splits into two questions you can answer separately:
- Where to look: every node of
rootis a candidate starting point. Visit them all with a simple recursive traversal. - What to check there: "is the tree starting at this node exactly the same as
subRoot?" That's the Same Tree problem, which you already know.
isSubtree(node):
node is empty → false (nothing starts here)
isSameTree(node, subRoot) → true (found it)
otherwise → isSubtree(node.left) OR isSubtree(node.right)Step by step
Example 2: root = [3, 4, 5, 1, 2, null, null, null, null, 0], subRoot = [4, 1, 2]:
| Candidate node | isSameTree(candidate, subRoot)? |
|---|---|
3 | 3 ≠ 4 → no |
4 | 4 = 4, left 1 = 1 ✅, right: 2 = 2 but root's 2 has a child 0 and subRoot's 2 doesn't → no |
1 | 1 ≠ 4 → no |
2 | 2 ≠ 4 → no |
0 | 0 ≠ 4 → no |
5 | 5 ≠ 4 → no |
No candidate matched, so the answer is false.
The code
The reference solution is below, with comments on every important line. It contains its own copy of isSameTree.
How fast is it?
With n nodes in root and m in subRoot:
- Time: O(n · m) in the worst case: a Same Tree check of up to
mnodes at each ofnnodes. In practice, most checks fail on the first node (different value), so it's much faster. - Memory: O(h) for the recursion, where
his the height ofroot.
Common mistakes
- Only matching the top part. The candidate's entire subtree must match, including what's below. Same Tree handles this, because it also requires
nullto matchnull. - Checking only the root.
subRootcan start anywhere, so you must try every node. - Comparing values instead of structure. Two trees can contain the same values in different shapes.
Going deeper
A faster approach: serialize and search. Turn both trees into strings (for example, in preorder), then check whether one string contains the other. With a fast string search like KMP, that's O(n + m). Two details make it correct:
- Write
nullmarkers, or[1, 2]and[1, null, 2]become the same string. - Put a separator before each value (like
,12and,2), or the tree12would "contain" the tree2.
Reference solution
// Same Tree: same shape and same values, all the way down.
function isSameTree(p, q) {
if (!p || !q) return p === q // both empty → same; only one empty → different
return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}
/**
* @param {TreeNode | null} root
* @param {TreeNode | null} subRoot
* @return {boolean}
*/
export default function isSubtree(root, subRoot) {
// Ran out of tree: subRoot can't start here.
if (!root) return false
// Does the tree starting at THIS node match? If not, try every node below.
return (
isSameTree(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)
)
}// Same Tree: same shape and same values, all the way down.
function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
if (!p || !q) return p === q // both empty → same; only one empty → different
return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}
export default function isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean {
// Ran out of tree: subRoot can't start here.
if (!root) return false
// Does the tree starting at THIS node match? If not, try every node below.
return (
isSameTree(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)
)
}def is_same_tree(p: TreeNode | None, q: TreeNode | None) -> bool:
# Same Tree: same shape and same values, all the way down.
if p is None or q is None:
return p is q # both empty → same; only one empty → different
return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)
def is_subtree(root: TreeNode | None, sub_root: TreeNode | None) -> bool:
# Ran out of tree: sub_root can't start here.
if root is None:
return False
# Does the tree starting at THIS node match? If not, try every node below.
return (
is_same_tree(root, sub_root)
or is_subtree(root.left, sub_root)
or is_subtree(root.right, sub_root)
)