Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Trees

Subtree of Another Tree

EASY✓ CHIP-TIMEDLC #572 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Decide whether one binary tree appears anywhere inside another, rooted at some node — same shape and values from that node down, exactly.

Two binary trees arrive — a larger one and a candidate — and the task is to decide whether the candidate appears somewhere inside the larger tree, rooted at some node within it.

"Appears" means an exact match from that starting node downward: the same values in the same shape, with no extra or missing children anywhere in that portion of the larger tree.

The candidate matching the larger tree's root counts just as well as matching some node buried deeper — the whole larger tree is fair game as a starting point for the comparison.

  • the larger tree can hold up to a few thousand nodes, the candidate up to a few hundred
  • node values can be negative, zero, or positive
  • a match must be exact from the matching node downward, not merely value-similar
EX 01
root = [4] · subRoot = [4]
→ true
two matching single nodes
EX 02
root = [4] · subRoot = [5]
→ false
two single nodes, different value
EX 03
root = [3, 4, 5, 1, 2] · subRoot = [4, 1, 2]
→ true
target matches a left subtree exactly

The hintstake only what you need

HINT 1 THE NUDGE

'Appears somewhere' means checking every node of the big tree as a possible starting point. What check do you already know for 'do these two trees match exactly'?

HINT 2 THE STRUCTURE

At each node of the big tree, ask: does the subtree rooted here match the target tree exactly? If not, move on and ask the same question of its children.

HINT 3 ONE STEP FROM THE ANSWER

That's O(n·m) in the worst case. To do better, flatten both trees into strings — with a null marker for every missing child, so shapes can't be confused — and ask whether one string contains the other.

Coach's boardthe pattern, step by step

THE SERIALIZED SEARCHPATTERN · SERIALIZE AND SEARCHroot = [3, 4, 5, 1, 2] · subRoot = [4, 1, 2]
STEP 1

Serialize both trees with null markers so shape can't be faked, then check whether the target's signature is a substring of the big tree's. Start by encoding the target: root 4, left 1, right 2.

STEP 1 / 6 · ← → WORK TOO

The splitstwo paces, two languages

grind/subtree-of-another-tree.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        def serialize(node):
            if not node:
                return ",#"
            return "," + str(node.val) + serialize(node.left) + serialize(node.right)

        return serialize(subRoot) in serialize(root)
TIME O(N+M)SPACE O(N+M)PYTHON · RACE PACE · 8 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED