LeetCode 112: Path Sum — Python Solution

LeetCode 112: Path Sum is an Easy binary tree general problem. This Python walkthrough develops a remaining-sum DFS 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 patternremaining-sum DFS
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, subtract each node value and accept only when a leaf makes the remaining target exactly zero. The invariant worth writing beside the code is: The remaining value equals the target minus the sum along the current root-to-node path.

Step-by-step algorithm

  1. Identify the input state consumed by hasPathSum(root, targetSum) and initialize the data required by the remaining-sum DFS pattern.
  2. Subtract each node value and accept only when a leaf makes the remaining target exactly zero.
  3. After each update, verify the page’s central invariant: The remaining value equals the target minus the sum along the current root-to-node path.
  4. Finish only after the boundary behavior is covered: A matching internal node is not enough; the path must end at a leaf.

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 hasPathSum(self, root, targetSum):
        if not root:
            return False
        remaining = targetSum - root.val
        if not root.left and not root.right:
            return remaining == 0
        return self.hasPathSum(root.left, remaining) or self.hasPathSum(root.right, remaining)

Reading the implementation

The main entry point is hasPathSum(root, targetSum). The named working state includes remaining; those variables make the remaining-sum DFS state visible instead of hiding it in incidental control flow.

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, subtract each node value and accept only when a leaf makes the remaining target exactly zero.

Correctness argument

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

Inductive step. Subtract each node value and accept only when a leaf makes the remaining target exactly zero. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so the remaining value equals the target minus the sum along the current root-to-node path.

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().hasPathSum(tree([5,4,8,11,None,13,4,7,2,None,None,None,1]),22)

Common mistakes and edge cases

  • Problem-specific boundary: A matching internal node is not enough; the path must end at a leaf.
  • 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 the remaining value equals the target minus the sum along the current root-to-node path.

Interview review checklist

  • Explain why remaining-sum DFS matches the structure of this input.
  • State the invariant in one sentence before tracing code: The remaining value equals the target minus the sum along the current root-to-node path.
  • Derive O(n) time and O(h) recursion space from how many times each element or state is visited.
  • Test the boundary explicitly: A matching internal node is not enough; the path must end at a leaf.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 114. Flatten Binary Tree to Linked List · Next: 129. Sum Root to Leaf Numbers