-
Notifications
You must be signed in to change notification settings - Fork 1
/
pathSum-recursion.cpp
38 lines (37 loc) · 962 Bytes
/
pathSum-recursion.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
/**
* Definition for a binary tree node.
* 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>> paths;
vector<int> path;
helper(paths,path,root,sum);
return paths;
}
void helper(vector<vector<int>>& paths,vector<int> path, TreeNode* root,int sum){
if(root==NULL){
return;
}
sum -= root->val;
if ((root->left == NULL) && (root->right == NULL))
{
if(sum==0){
path.push_back(root->val);
paths.push_back(path);
}
return;
}
else{
path.push_back(root->val);
helper(paths,path,root->left,sum);
helper(paths,path,root->right,sum);
}
}
};