-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path113.txt
44 lines (31 loc) · 1.04 KB
/
113.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 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>> result;
vector<int> path;
path_sum(root,path,result,sum);
return result;
}
private:
void path_sum(TreeNode* root,vector<int>& path,vector<vector<int>>& result,int gap){
if(root == nullptr) return;
else
path.push_back(root -> val);
if(root -> left ==nullptr && root ->right == nullptr){
if (gap == root -> val) result.push_back(path);
}
int newgap = gap - root->val;
path_sum(root ->left, path, result,newgap);
path_sum(root ->right, path, result,newgap);
path.pop_back(); //回溯
}
};