-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPath Sum II.cpp
More file actions
38 lines (36 loc) · 968 Bytes
/
Path Sum II.cpp
File metadata and controls
38 lines (36 loc) · 968 Bytes
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
/**
* Definition for binary tree
* 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> > ret;
vector<int> buf;
travel(root, sum, buf, ret);
return ret;
}
private:
void travel(TreeNode *root, const int &sum, vector<int> buf, vector<vector<int> > &ret) {
if (!root) return;
buf.push_back(root->val);
if (!root->left && !root->right) {
if (sum(buf) == sum) ret.push_back(buf);
return;
}
travel(root->left, sum, buf, ret);
travel(root->right, sum, buf, ret);
}
int sum(const vector<int> &vec) {
int ret = 0;
std::for_each(vec.begin(), vec.end(), [&](int n){
ret += n;
});
return ret;
}
};