ToolMight Logo
EasyTrees & BSTTree Traversal DFSSame Tree Equality Check

Subtree of Another Tree

Check whether subRoot matches an entire subtree of root in structure and values. Compare double-DFS tree matching against O(n + m) pre-order serialization + substring search.

Optimal Time
O(n * m)
Optimal Space
O(h)
Primary Pattern
Tree Traversal DFS
Visualizer
Open Interactive View →

Problem Statement

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.

A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.

Examples & Constraints

Example 1
Input: root = [3, 4, 5, 1, 2], subRoot = [4, 1, 2]
Output: true
Explanation: The left child of node 3 has root 4 with left child 1 and right child 2, which matches subRoot exactly.
Example 2
Input: root = [3, 4, 5, 1, 2, null, null, null, null, 0], subRoot = [4, 1, 2]
Output: false
Explanation: Although node 4 has children 1 and 2, node 2 additionally has a child 0 in root, making the trees non-identical.
Constraints
  • The number of nodes in the root tree is in the range [1, 2000].
  • The number of nodes in the subRoot tree is in the range [1, 1000].
  • -10^4 <= root.val <= 10^4
  • -10^4 <= subRoot.val <= 10^4

Pattern Recognition & Core Invariant

How to Spot This Pattern

Exact subtree containment requires matching structure down to null leaves — solvable either by pairing outer traversal with isSameTree or by serializing trees with explicit delimiters and null tokens.

Core Invariant

A candidate node u matches subRoot iff its full pre-order serialization with null markers (#) and boundary delimiters (^val) matches subRoot's serialization verbatim.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Double Recursive DFS (Traversal + Equality)Optimal
O(n * m)O(h)Traverse every candidate node in root with DFS. At each node, check if the subtree rooted there is strictly identical (isSameTree) to subRoot in structure and node values.
2. Pre-Order Serialization + Substring MatchOptimal
O(n + m)O(n + m)Serialize both trees in pre-order using unique leading delimiters and explicit null markers (#), then test substring containment in linear O(n + m) time.

1. Double Recursive DFS (Traversal + Equality)

Optimal
TimeO(n * m)
SpaceO(h)

Traverse every candidate node in root with DFS. At each node, check if the subtree rooted there is strictly identical (isSameTree) to subRoot in structure and node values.

Time ComplexityO(n * m)

Where N is the number of nodes in root and M is the number of nodes in subRoot. In the worst case (e.g. repeated identical values), isSameTree is called for every node in root.

Space ComplexityO(h)

Consumes memory on the call stack proportional to the height H of root (at most O(n) for a skewed tree, O(log n) for a balanced tree).

How It Works

The Two-Level Recursive Strategy

This problem requires two distinct recursive functions working in tandem:

  1. Helper Function: `isSameTree(s, t)`:
  • Compares if two trees are completely isomorphic (identical structure and values):
  • If both s == null and t == null, return true (both empty).
  • If only one is null, or if s.val != t.val, return false.
  • Recurse: isSameTree(s.left, t.left) && isSameTree(s.right, t.right).
  1. Main Function: `isSubtree(root, subRoot)`:
  • If subRoot == null, an empty tree is trivially a subtree of any tree; return true.
  • If root == null, an empty main tree cannot contain a non-empty subRoot; return false.
  • If isSameTree(root, subRoot) is true, we found a match! Return true.
  • Otherwise, check if subRoot matches anywhere in the left subtree OR right subtree: isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot).

Strict Subtree Invariant: No Stray Descendants

A common mistake is returning true if subRoot is a subset of root. The definition requires the subtree to include all of the candidate node's descendants. The isSameTree equality check ensures that if subRoot has null children, the matched candidate must also have null children at those exact positions.

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Inspect root (3)

Compare tree at 3 with subRoot (4). 3 != 4 -> isSameTree fails. Recurse into children of 3.

State:isSubtree(3.left, subRoot) || isSubtree(3.right, subRoot)
Strengths
  • +Clean modular recursion pattern
  • +Zero extra serialized string allocation
Trade-offs
  • -Worst-case O(n * m) time on trees with many duplicate node values

Reference Implementation

Complete implementation for Double Recursive DFS (Traversal + Equality) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_same_tree(s: TreeNode | None, t: TreeNode | None) -> bool:
if not s and not t:
return True
if not s or not t or s.val != t.val:
return False
return is_same_tree(s.left, t.left) and is_same_tree(s.right, t.right)
def is_subtree(root: TreeNode | None, sub_root: TreeNode | None) -> bool:
if not sub_root:
return True
if not root:
return False
if is_same_tree(root, sub_root):
return True
return is_subtree(root.left, sub_root) or is_subtree(root.right, sub_root)
if __name__ == "__main__":
# root: [3, 4, 5, 1, 2]
root = TreeNode(3)
root.left = TreeNode(4, TreeNode(1), TreeNode(2))
root.right = TreeNode(5)
# subRoot: [4, 1, 2]
sub_root = TreeNode(4, TreeNode(1), TreeNode(2))
print("Is Subtree:", is_subtree(root, sub_root))

2. Pre-Order Serialization + Substring Match

Optimal
TimeO(n + m)
SpaceO(n + m)

Serialize both trees in pre-order using unique leading delimiters and explicit null markers (#), then test substring containment in linear O(n + m) time.

Time ComplexityO(n + m)

Serializing both trees takes O(n + m), and KMP substring matching runs in O(n + m) worst-case time.

Space ComplexityO(n + m)

Stores serialized representations of both trees.

How It Works

Turning Tree Equality into String Matching

A pre-order traversal that records every `null` leaf (#) uniquely encodes both tree shape and values. However, one subtlety breaks naive string builders:

  • Suppose root is node 12 and subRoot is node 2.
  • "12,#,#" contains "2,#,#" as a substring even though 12 != 2!

Prefixing every value with a delimiter like ^ (^12,#,# vs ^2,#,#) makes each serialized subtree completely unambiguous, reducing isSubtree to substring search (KMP or native linear search) in `O(n + m)` time.

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Serialize subRoot [4, 1, 2]

Pre-order with '^' delimiters and '#' nulls yields "^4^1##^2##".

State:sub = "^4^1##^2##"
Strengths
  • +Drops worst-case runtime from O(n * m) down to O(n + m) linear time
  • +Concise and clean to verify with explicit delimiters
Trade-offs
  • -Allocates O(n + m) strings for serialized representations

Reference Implementation

Complete implementation for Pre-Order Serialization + Substring Match in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def serialize(node) -> str:
tokens = []
def dfs(cur):
if not cur:
tokens.append("#")
return
tokens.append(f"^{cur.val}")
dfs(cur.left)
dfs(cur.right)
dfs(node)
return "".join(tokens)
def is_subtree_serial(root, sub_root) -> bool:
return serialize(sub_root) in serialize(root)
Interactive Visualizer

Trace Binary Search Tree mechanics in memory

Step through custom inputs in the Binary Search Tree visualizer to inspect pointer updates, array shifts, and call-stack state alongside Subtree of Another Tree.

Open Binary Search Tree visualizer

Frequently Asked Questions

What is the difference between a subtree and a subset of nodes?

A subtree rooted at u contains u and ALL of u's descendants down to their leaves. An extra child anywhere under u that isn't in subRoot disqualifies the match.

Why must pre-order serialization include a leading delimiter like '^'?

Without a token separator before each integer, node [12] serializes to "12##" which incorrectly contains [2]'s "2##" as a substring. Adding ^ turns them into "^12##" vs "^2##".

When is DFS `O(n * m)` faster than `O(n + m)` serialization in practice?

On random trees with distinct integers, isSameTree aborts immediately at the first node value mismatch, requiring near-zero extra memory compared to serializing both full strings.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Value substring collision (`root = [12]`, `subRoot = [2]`): serializing without leading delimiters wrongly matches `2` inside `12`!
  • Partial prefix tree: `root` node has children `[1, 2]` where `2` has child `0`, while `subRoot = [4, 1, 2]` has nulls under `2` (must return false).
  • Identical trees (`root == subRoot`) return true because a tree is a subtree of itself.

Common Bugs to Avoid

  • Serializing node values without leading delimiters (e.g. turning 12 into '12...' so '2...' triggers a false substring match).
  • Omitting explicit null markers (#) during serialization, which merges distinct tree shapes into identical sequences.
  • Stopping match verification before reaching null leaves in `isSameTree`.

Interview Follow-Up Variations

  • Subtree Merkle Hashing: hash `(node.val, leftHash, rightHash)` in bottom-up DFS to compare large trees in O(n + m) expected time.
  • Find Duplicate Subtrees: map serialized/hashed subtrees into a frequency dictionary.

Related Problems

All problems
EasyTrees & BST

Maximum Depth of Binary Tree

Compute the maximum depth (node count along longest root-to-leaf path) of a binary tree using recursive post-order DFS and iterative level-order BFS.

Pattern: Depth-First Search (DFS)
O(n) · O(h)
Solve
EasyTrees & BST

Invert Binary Tree

Mirror a binary tree around its vertical axis by swapping left and right child pointers via recursive DFS or iterative level-order BFS.

Pattern: DFS Traversal
O(n) · O(h)
Solve
MediumTrees & BST

Binary Tree Level Order Traversal

Group binary tree node values level-by-level from left to right. Compare FIFO queue level batching against depth-indexed DFS recursion.

Pattern: Breadth-First Search (BFS)
O(n) · O(w)
Solve