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
- Both None: true. Exactly one None: false.
- Compare the values, then recurse on both left children and both right children.
- 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.