# 113. Path Sum II

## 1.問題

![](/files/-LJ9JGyptPsUkNhTqlLh)

## 2.想法

* 如同112.Path sum的作法
  * pre-order
  * Recursion:
    * 每次都將sum減去自己的值, 當左子node與右子node都為NULL時, 回傳sum == root->val
    * 如果左子node不為NULL, 將左子node作為input
    * 如果右子node不為NULL, 將右子node作為input
* 再加上ray tracking
  * 注意record作為參數時不要加&

## 3.程式碼

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res; 
        if (!root) {
            return res;
        }
        vector<int> record;
        pathSum(res, record, root, sum);
        
        return res;
    }
private:
    void pathSum(vector<vector<int>>& res, vector<int> record, TreeNode* root, int sum) {
        if (!root && sum == 0) {
            res.push_back(record);
            return;
        }
        
        record.push_back(root->val);
        
        if (!root->left && !root->right && sum == root->val) {
            res.push_back(record);
            return;
        }
        
        if (root->left) {
            pathSum(res, record, root->left, sum - root->val);
        }
        
        if (root->right) {
            pathSum(res, record, root->right, sum - root->val);
        }
    }
};
```

## 4.Performance

![](/files/-LJ9KKXA5kPQ6JpgffGc)


---

# 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://jenhsuan.gitbook.io/algorithm/leetcode/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.
