forked from fanfank/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
path-sum-ii.cpp
40 lines (39 loc) · 1015 Bytes
/
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:
vector<int> v;
vector<vector<int> > vv;
vector<vector<int> > pathSum(TreeNode *root, int sum) {
// Note: The Solution object is instantiated only once and is reused by each test case.
v.clear(), vv.clear();
pathSums(root, 0, sum);
return vv;
}
private:
void pathSums(TreeNode *root, int sum, const int ans) {
if(root == 0)
return;
v.push_back(root->val);
sum += root->val;
bool isLeaf = true;
if(root->left) {
isLeaf = false;
pathSums(root->left, sum, ans);
}
if(root->right) {
isLeaf = false;
pathSums(root->right, sum, ans);
}
if(isLeaf && sum == ans)
vv.push_back(v);
v.pop_back();
}
};