forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Path_Sum_II.cc
44 lines (44 loc) · 1.16 KB
/
Path_Sum_II.cc
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 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
(this->ans).clear();
this->tarSum = sum;
if (root == NULL) {
return this->ans;
}
vector<int> path;
dfs(root, path, 0);
return ans;
}
private:
vector<vector<int> > ans;
int tarSum;
void dfs(TreeNode *root, vector<int> &path, int total) {
total += root->val;
path.push_back(root->val);
if (root->left == NULL && root->right == NULL && total == this->tarSum) {
(this->ans).push_back(path);
path.pop_back();
return;
}
if (root->left) {
dfs(root->left, path, total);
}
if (root->right) {
dfs(root->right, path, total);
}
path.pop_back();
return;
}
};