TRT
Sign in
easyCoreLeetCode#parallel recursion

Same tree

Decide whether two binary trees have the same shape and the same values, by recursing on both at once.

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

inp = [1, 2, 3], q = [1, 2, 3]

outtrue

inp = [1, 2], q = [1, null, 2]

outfalse

inp = [1, 2, 1], q = [1, 1, 2]

outfalse

Given the roots of two binary trees, return whether they are structurally identical with equal values at every node.

Before you code

Two trees are the same if both are empty, or both have the same root value and the same left and right subtrees. That definition is the recursion.

Hints

  1. Both None: true. Exactly one None: false.
  2. Compare the values, then recurse on both left children and both right children.
  3. The recursion stops at the first difference, so it is O(min(m, n)).

Production & complexity notes

When solving Same 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

Recursing on two trees in parallel, from Tree recursion patterns.

Not started

Sign in to save your learning progress.

Sign in to save