> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Path Sum II Python Solution with Tests

> Tested Python solution for LeetCode 113 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 113, Medium. Topics: Backtracking, Tree, Depth-First Search, Binary Tree. [View on LeetCode](https://leetcode.com/problems/path-sum-ii/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 113   # by problem number
lcpy gen -s path_sum_ii   # by problem name
```

## Problem

Given the `root` of a binary tree and an integer `targetSum`, return all **root-to-leaf** paths where the sum of the node values in the path equals `targetSum`. Each path should be returned as a list of the node **values**, not node references.

A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg)

```
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
Explanation: There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
```

![Example 2](https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg)

```
Input: root = [1,2,3], targetSum = 5
Output: []
```

```
Input: root = [1,2], targetSum = 0
Output: []
```

### Constraints

* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/path_sum_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/path_sum_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Solution:
    # Time: O(n) - visit each node once
    # Space: O(h) - recursion depth + path storage, where h is tree height
    def path_sum(self, root: TreeNode[int] | None, target_sum: int) -> list[list[int]]:
        result: list[list[int]] = []

        def dfs(node: TreeNode[int] | None, remaining: int, path: list[int]) -> None:
            if not node:
                return

            # Add current node to path
            path.append(node.val)

            # Check if leaf node with target sum
            if not node.left and not node.right and remaining == node.val:
                result.append(path[:])

            # Recurse on children with updated remaining sum
            dfs(node.left, remaining - node.val, path)
            dfs(node.right, remaining - node.val, path)

            # Backtrack: remove current node from path
            path.pop()

        dfs(root, target_sum, [])
        return result
```

## Complexity

| Time                        | Space                                                         |
| --------------------------- | ------------------------------------------------------------- |
| O(n) - visit each node once | O(h) - recursion depth + path storage, where h is tree height |

## Tags

[Grind](/catalog/grind).
