Skip to content
mlmentorship

Subtree of Another Tree

Locate candidate roots, verify every value and child position, and distinguish exact subtree equality from partial-pattern matching.

Published · 17 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Subtree of Another Tree

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Search each main-tree node as a candidate root, then require equal values and equal left and right topology.

Problem trace

An exact subtree match includes missing children, not just matching values

Input and goalCheck whether one full tree appears inside another tree.
Start at the main rootCall is_subtree(main3, sub4); same compares roots 3 and 4 before any child search.
Main treePatternfirst=main3second=sub4Exact match includes all missing children34512412
Original child-slot inventory
nodevalueleft childright childmain33first-> main4-> main5main44-> main1-> main2main11-> null-> nullmain22-> null-> nullmain55-> null-> nullsub44second-> sub1-> sub2sub11-> null-> nullsub22-> null-> null
mainTreemain3(main4(main1,main2),main5)subTreesub4(sub1,sub2)callStackis_subtree(main3, sub4) -> same(main3, sub4)comparison3 != 4
first
(1, 1)
second
(6, 1)
main tree
main3(main4(main1,main2),main5)

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.
Call is_subtree(main3, sub4); same compares roots 3 and 4 before any child search. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why would an extra child below the candidate invalidate the match even if every pattern value is present?
Full interview answer 17 min read

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 pairRequired evidence
Main 3 versus pattern 4Different values: reject this candidate
Main 4 versus pattern 4Equal roots: compare both child pairs
Main 1 versus pattern 1Equal values and both null pairs
Main 2 versus pattern 2Equal values and both null pairs
Completed candidate at path LReturn True; skip main node 5

Problem trace

An exact subtree match includes missing children, not just matching values

Worked example: equal candidate roots still require a complete local tree matchBoth candidate roots store 5 and have left child 3. An extra right child 7 means the larger local tree is not equal to the proposed subtree.Child positions and missing childrenbelong to the structureWanted subtree has no right child53#Missing children count too.Candidate has an extra right childseven537Missing children count too.
Read it this way: Both candidate roots store 5 and have left child 3. An extra right child 7 means the larger local tree is not equal to the proposed subtree. Does the extra right child disappear merely because both candidate roots equal five?
Reference drawing

Problem trace

An exact subtree match includes missing children, not just matching values

Worked example: equal candidate roots still require a complete local tree matchBoth candidate roots store 5 and have left child 3. An extra right child 7 means the larger local tree is not equal to the proposed subtree.Child positions and missing childrenbelong to the structureWanted subtree has no right child53#Missing children count too.Candidate has an extra right childseven537Missing children count too.
Execution trace
Input and goalCheck whether one full tree appears inside another tree.
Start at the main rootCall is_subtree(main3, sub4); same compares roots 3 and 4 before any child search.
Main treePatternfirst=main3second=sub4Exact match includes all missing children34512412
Original child-slot inventory
nodevalueleft childright childmain33first-> main4-> main5main44-> main1-> main2main11-> null-> nullmain22-> null-> nullmain55-> null-> nullsub44second-> sub1-> sub2sub11-> null-> nullsub22-> null-> null
mainTreemain3(main4(main1,main2),main5)subTreesub4(sub1,sub2)callStackis_subtree(main3, sub4) -> same(main3, sub4)comparison3 != 4
first
(1, 1)
second
(6, 1)
main tree
main3(main4(main1,main2),main5)

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.
Call is_subtree(main3, sub4); same compares roots 3 and 4 before any child search. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why would an extra child below the candidate invalidate the match even if every pattern value is present?
Read it this way: Both candidate roots store 5 and have left child 3. An extra right child 7 means the larger local tree is not equal to the proposed subtree. Does the extra right child disappear merely because both candidate roots equal five?

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.