Determine whether one complete binary tree occurs as a rooted subtree inside another tree.
Problem
Input. A main binary tree and a pattern binary tree, both finite and without cycles or shared children.
Output. Return True if some main-tree node roots a subtree exactly equal to the pattern; otherwise return False.
Rules. Matching requires equal values and identical left/right structure, including all missing children. You cannot ignore extra descendants below a chosen root. Preserve both trees. An empty pattern matches anywhere, including an empty main tree; a nonempty pattern cannot match an empty main tree.
Example. A node 4 with leaf children 1 and 2 matches a pattern with exactly that structure. If the pattern’s node 2 is a leaf but the main node 2 has an extra child, that candidate fails.
Picture
Compare main root three with pattern root four. That candidate fails immediately; try the main tree’s left child next.
| Candidate or pair | Required evidence |
|---|---|
| Main 3 versus pattern 4 | Different values: reject this candidate |
| Main 4 versus pattern 4 | Equal roots: compare both child pairs |
| Main 1 versus pattern 1 | Equal values and both null pairs |
| Main 2 versus pattern 2 | Equal values and both null pairs |
Completed candidate at path L | Return True; skip main node 5 |
Problem trace
An exact subtree match includes missing children, not just matching values
Reference drawing
Problem trace
An exact subtree match includes missing children, not just matching values
Execution trace
Original child-slot inventory
- first
- (1, 1)
- second
- (6, 1)
- main tree
- main3(main4(main1,main2),main5)
Original child-slot inventory
- first
- (1, 1)→(2, 1)
- second
- (6, 1)→not shown
- call stack
- is_subtree(main3, sub4) -> same(main3, sub4)→is_subtree(main3, sub4) -> is_subtree(main4, sub4)
Original child-slot inventory
- second
- not shown→(6, 1)
- visited
- not shown→[main4, sub4]
- call stack
- is_subtree(main3, sub4) -> is_subtree(main4, sub4)→same(main4, sub4) -> same(main1, sub1)
Original child-slot inventory
- first
- (2, 1)→(3, 1)
- second
- (6, 1)→(7, 1)
- visited
- [main4, sub4]→[main4, sub4, main1, sub1]
Original child-slot inventory
- first
- (3, 1)→(4, 1)
- second
- (7, 1)→(8, 1)
- visited
- [main4, sub4, main1, sub1]→[main4, sub4, main1, sub1, main2, sub2]
Original child-slot inventory
- first
- (4, 1)→(2, 1)
- second
- (8, 1)→(6, 1)
- call stack
- not shown→same(main4, sub4) -> true
- Recognize it
- Use this composition when one complete rooted tree must appear inside another: candidate roots may occur anywhere, but a candidate succeeds only if every value and missing-child position matches.
- Keep true
- is_subtree searches every reachable candidate root until one same call succeeds; same(first, second) returns true exactly when the two rooted trees have equal values and recursively identical left and right topology.
- Reuse it
- Separate locate from verify: DFS locates candidate roots, then a stricter recursive predicate proves complete structure; the same composition applies to tree patterns, AST fragments, and directory subtrees.
Code
Use this node type for a local run.
from dataclasses import dataclass
@dataclass
class TreeNode:
val: int
left: "TreeNode | None" = None
right: "TreeNode | None" = None
def is_subtree(root: TreeNode | None, subroot: TreeNode | None) -> bool:
def same(first: TreeNode | None, second: TreeNode | None) -> bool:
if first is None or second is None:
return first is second
return (
first.val == second.val
and same(first.left, second.left)
and same(first.right, second.right)
)
if subroot is None:
return True
if root is None:
return False
return (
same(root, subroot)
or is_subtree(root.left, subroot)
or is_subtree(root.right, subroot)
)
Separate Locate from Verify
The outer OR tries the current root, then left, then right. Its first success stops further candidate search.
The inner AND requires equal values and exact equality of both aligned child pairs. One missing child matches only another missing child.
An extra descendant under candidate node two breaks the match, even when all pattern values remain visible.
Count Repeated Verification
For nonempty trees of sizes and , worst-case time is .
Many candidate roots can repeat almost the same long comparison before failing. One outer traversal does not imply linear total work.
Active recursion is bounded by the main-tree height plus base-case frames: stack space. Deep trees can exceed Python’s recursion limit.
The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.
Recall: What does equal root value prove? Only that this candidate deserves child comparisons, not that the rooted trees match.
Return Every Exact Candidate Path
Choose this when: A Boolean answer does not provide enough location evidence.
Paths use L and R; the empty string identifies the main root. Traverse left before right and retain exact null semantics.
def subtree_paths(root, subroot):
def equal(first, second):
if first is None or second is None:
return first is second
return (
first.val == second.val
and equal(first.left, second.left)
and equal(first.right, second.right)
)
if subroot is None:
return []
answer = []
stack = [] if root is None else [(root, "")]
while stack:
node, path = stack.pop()
if equal(node, subroot):
answer.append(path)
if node.right is not None:
stack.append((node.right, path + "R"))
if node.left is not None:
stack.append((node.left, path + "L"))
return answer
This interface locates nonempty patterns only; an empty pattern returns no candidate paths.
The pictured result is ["L"]. Two equal-valued leaves in different branches produce distinct paths.
Verification can still take time. Path copies can add time.
Pending strings can need working characters, plus returned paths. The recursive verifier retains its depth limit.
Permit Omitted Pattern Descendants
Choose this when: Missing pattern children explicitly mean “no restriction.”
def contains_partial_tree(root, pattern):
def matches(node, wanted):
if wanted is None:
return True
if node is None:
return False
return (
node.val == wanted.val
and matches(node.left, wanted.left)
and matches(node.right, wanted.right)
)
if pattern is None:
return True
if root is None:
return False
return (
matches(root, pattern)
or contains_partial_tree(root.left, pattern)
or contains_partial_tree(root.right, pattern)
)
Pattern root one with left child two matches main root one with children two and three. Exact equality rejects that candidate.
A required right child four still fails against right child three. Extra descendants are allowed; wrong required values are not.
Worst-case time remains and recursive space . This is partial matching, not exact subtree equality.