forked from daizhenyang/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPath Sum II.cpp
More file actions
44 lines (44 loc) · 1.05 KB
/
Path Sum II.cpp
File metadata and controls
44 lines (44 loc) · 1.05 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
/**
* 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> >ans;
void dfs(TreeNode *r,int t,vector<int>a)
{
if (!r)return;
if (!r->left&&!r->right)
{
if (!t)ans.push_back(a);
return;
}
if (r->left)
{
a.push_back(r->left->val);
dfs(r->left,t-r->left->val,a);
a.pop_back();
}
if (r->right)
{
a.push_back(r->right->val);
dfs(r->right,t-r->right->val,a);
a.pop_back();
}
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root)return vector<vector<int> >();
vector<int>a;
a.push_back(root->val);
ans.clear();
dfs(root,sum-root->val,a);
return ans;
}
};