-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath_sum2.cpp
More file actions
44 lines (43 loc) · 1.4 KB
/
path_sum2.cpp
File metadata and controls
44 lines (43 loc) · 1.4 KB
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
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<TreeNode *> cur;
int cs;
int sum;
vector<vector<int> > ps;
void helper(TreeNode *r) {
if (r->left == NULL && r->right == NULL) {
if (r->val + cs == sum) {
vector<int> tmp;
for (auto i = cur.begin(); i != cur.end(); i++)
tmp.push_back((*i).val);
tmp.push_back(r->val);
ps.emplace_back(tmp);
}
} else {
cs += r->val;
cur.push_back(r);
if (r->left) {
helper(r->left);
}
if (r->right) {
helper(r->right);
}
cs -= r->val;
cur.pop_back();
}
}
vector<vector<int> > pathSum(TreeNode *root, int s) {
if (root == NULL)
return ps;
sum = s;
cs = 0;
helper(root);
return ps;
}
};