# 113. Path Sum II

## 1.問題

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJ91PFycCq0rOszH6wv%2F-LJ9JGyptPsUkNhTqlLh%2F2018080505.jpg?alt=media\&token=d9c2d7b9-d523-44b4-8b9b-4763ef7e7713)

## 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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LJ91PFycCq0rOszH6wv%2F-LJ9KKXA5kPQ6JpgffGc%2F2018080506.jpg?alt=media\&token=2e0ab514-4b31-468d-8388-8fb6e202168d)
