-
Notifications
You must be signed in to change notification settings - Fork 28
/
Path_Sum_II.cpp
40 lines (34 loc) · 1.07 KB
/
Path_Sum_II.cpp
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void build(TreeNode *root, vector<vector<int> > &result, vector<int> &solution, int sum) {
if(!root) return;
if(!root->left and !root->right) {
if(root->val == sum) {
solution.push_back(root->val);
result.push_back(solution);
solution.pop_back();
}
return;
}
solution.push_back(root->val);
if(root->left) build(root->left, result, solution, sum - root->val);
if(root->right) build(root->right, result, solution, sum - root->val);
solution.pop_back();
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > res;
if(!root) return res;
vector<int> sol;
build(root, res, sol, sum);
return res;
}
};