TRT
Sign in
easyCoreLeetCode#same tree from every node#serialization

Subtree of another tree

Decide whether one tree appears as a subtree of another, by running a same-tree check from every node.

The Runtime Theory Team1 min read
Taught inTree recursion patternsPro — members onlyMost tree problems are solved by one of three recursive shapes: combine the children's answers on the way up, pass information down from the root, or return one value while updating a global best.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inroot = [3, 4, 5, 1, 2], subRoot = [4, 1, 2]

outtrue

inroot = [3, 4, 5, 1, 2, null, null, null, null, 0], subRoot = [4, 1, 2]

outfalse

inroot = [1, 1], subRoot = [1]

outtrue

Given two binary trees, root and subRoot, return whether some node of root has a subtree identical to subRoot.

Before you code

A subtree must match all the way down: in the second example, 4's subtree has an extra node 0, so it doesn't match. Reuse a same-tree check.

Hints

  1. is_subtree(root, sub) is true if same(root, sub), or if sub is a subtree of root's left or right child.
  2. This is O(m × n) in the worst case.
  3. Faster: serialize both trees with null markers and check whether one string contains the other, using a linear-time string search.

Production & complexity notes

When solving Subtree of another tree on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Tree recursion patterns to reinforce the underlying pattern.

What it practices

Combining two recursive functions, from Tree recursion patterns.

Not started

Sign in to save your learning progress.

Sign in to save