LeetCode 100: Same Tree — Python Solution

LeetCode 100: Same Tree is an Easy binary tree general problem. This Python walkthrough develops a paired recursion solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyEasy
TopicBinary Tree General
Reusable patternpaired recursion
ComplexityO(n) time and O(h) recursion space

Recognizing the pattern

Tree recursion works when the return value has one precise meaning for every subtree; the parent can then combine child results locally.

For this problem specifically, two nodes match when both are absent, or both exist with equal values and matching left and right subtrees. The invariant worth writing beside the code is: Every recursive pair represents corresponding positions in the two trees.

Step-by-step algorithm

  1. Identify the input state consumed by isSameTree(p, q) and initialize the data required by the paired recursion pattern.
  2. Two nodes match when both are absent, or both exist with equal values and matching left and right subtrees.
  3. After each update, verify the page’s central invariant: Every recursive pair represents corresponding positions in the two trees.
  4. Finish only after the boundary behavior is covered: One missing node immediately distinguishes the structures.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

class Solution:
    def isSameTree(self, p, q):
        if not p or not q:
            return p is q
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Reading the implementation

The main entry point is isSameTree(p, q). The implementation keeps little named state because each operation can be resolved directly from the current input position.

The entry point is recursive: each call reduces the remaining tree, graph, or search state before combining the returned information. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, two nodes match when both are absent, or both exist with equal values and matching left and right subtrees.

Correctness argument

Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.

Inductive step. Two nodes match when both are absent, or both exist with equal values and matching left and right subtrees. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so every recursive pair represents corresponding positions in the two trees.

Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.

Complexity and trade-offs

O(n) time and O(h) recursion space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

An explicit stack avoids recursion-depth limits, but it must carry the same state that recursive call frames provide automatically. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().isSameTree(tree([1,2,3]),tree([1,2,3]))

Common mistakes and edge cases

  • Problem-specific boundary: One missing node immediately distinguishes the structures.
  • Pattern-level pitfall: Write the empty-subtree result first and keep returned subtree information separate from any global answer updated at a node.
  • Invariant check: after every update, confirm that every recursive pair represents corresponding positions in the two trees.

Interview review checklist

  • Explain why paired recursion matches the structure of this input.
  • State the invariant in one sentence before tracing code: Every recursive pair represents corresponding positions in the two trees.
  • Derive O(n) time and O(h) recursion space from how many times each element or state is visited.
  • Test the boundary explicitly: One missing node immediately distinguishes the structures.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 104. Maximum Depth of Binary Tree · Next: 226. Invert Binary Tree