AlgoInsight

DSA problem

Subtree of Another Tree

EasyTree Traversal - Pre OrderPattern: Tree Traversal - Pre Ordertop600AmazonMicrosoftGoogleBloombergApple

Given the roots of two binary trees root and subRoot, return true if there is any subtree of root that is structurally identical and node-wise equal to subRoot. A subtree of a tree consists of a node and all of that node's descendants — the subtree must match subRoot exactly in shape and values.

This decomposes naturally into two preorder traversals. First, define isSame(a, b) that decides whether two subtrees are identical (the standard Same-Tree recurrence). Then walk root in preorder: at each node, ask "does isSame(node, subRoot) return true?" If so, return true. Otherwise, recurse into the left and right children.

Each call to isSame costs O(s) where s is the size of subRoot. We may invoke it at every one of the n nodes of root, giving a worst-case time of O(n * s). The space is O(h) for the outer recursion plus O(min(h, h_sub)) for the inner check — overall O(h).

An asymptotically faster technique serializes both trees to strings (with explicit null markers and delimiters to avoid ambiguities like "12" matching the start of "123") and then runs KMP substring search, giving O(n + s). For most inputs the simple recursive version is preferred for clarity, and the LeetCode test suite passes comfortably with it.

Examples

Example 1
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true
Explanation: The subtree rooted at the left child of 3 has the values 4 / 1, 2 — exactly equal to subRoot. Therefore subRoot appears as a subtree of root.
Example 2
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false
Explanation: The candidate left subtree of 3 has shape 4 / 1, 2 / 0 — the extra node 0 means it is no longer structurally identical to subRoot.
Example 3
Input: root = [1,1], subRoot = [1]
Output: true
Explanation: Either of the nodes valued 1 (the root or the left child) is itself a subtree equal to subRoot.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treedepth-first-searchrecursion

Browse all DSA problems