# 113 Path Sum II

## 113. Path Sum II

## 1. Question

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

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]
]
```

## 2. Implementation

(1) Backtracking

```java
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        getPathSum(root, 0, sum, path, res);
        return res;
    }

    public void getPathSum(TreeNode node, int depth, int sum, List<Integer> path, List<List<Integer>> res) {
        if (node == null) {
            return;
        }

        path.add(node.val);

        if (node.left == null && node.right == null && node.val == sum) {
            res.add(new ArrayList(path));
        }

        getPathSum(node.left, depth + 1, sum - node.val, path, res);
        getPathSum(node.right, depth + 1, sum - node.val, path, res);

        path.remove(path.size() - 1);
    }
}
```

## 3. Time & Space Complexity

Backtracking:


---

# 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://protegejj.gitbook.io/algorithm-practice/leetcode/tree/113-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.
