Skip to content

Commit 5f57a93

Browse files
committed
Create Path Sum II.cpp
1 parent 32e3480 commit 5f57a93

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Path Sum II.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* Definition for binary tree
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
vector<vector<int> >ans;
13+
void dfs(TreeNode *r,int t,vector<int>a)
14+
{
15+
if (!r)return;
16+
if (!r->left&&!r->right)
17+
{
18+
if (!t)ans.push_back(a);
19+
return;
20+
}
21+
if (r->left)
22+
{
23+
a.push_back(r->left->val);
24+
dfs(r->left,t-r->left->val,a);
25+
a.pop_back();
26+
}
27+
if (r->right)
28+
{
29+
a.push_back(r->right->val);
30+
dfs(r->right,t-r->right->val,a);
31+
a.pop_back();
32+
}
33+
}
34+
vector<vector<int> > pathSum(TreeNode *root, int sum) {
35+
// Start typing your C/C++ solution below
36+
// DO NOT write int main() function
37+
if (!root)return vector<vector<int> >();
38+
vector<int>a;
39+
a.push_back(root->val);
40+
ans.clear();
41+
dfs(root,sum-root->val,a);
42+
return ans;
43+
}
44+
};

0 commit comments

Comments
 (0)