# Path Sum II

## Problem

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

**Note:** A leaf is a node with no children.<br>

{% hint style="info" %}
For example:

Given the below binary tree and `sum = 22`,

```
      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1
```

Return:

```
[
   [5,4,11,2],
   [5,8,4,5]
]
```

{% endhint %}

## Solution

```
class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        currPath = []
        allPaths = []
        self.findPaths(root, sum, currPath, allPaths)
        return allPaths
        
    def findPaths(self, root, pathSum, currentPath, allPaths):
        if root is None:
            return 
        
        currentPath.append(root.val)
        if root.left == None and root.right == None and root.val == pathSum:
            allPaths.append(list(currentPath))
            
        self.findPaths(root.left, pathSum - root.val, currentPath, allPaths)
        self.findPaths(root.right, pathSum - root.val, currentPath, allPaths)
        
        del currentPath[-1]
            
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://joshualbarb.gitbook.io/leetcode-problems/tree-depth-first-search/path-sum-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
