-
Notifications
You must be signed in to change notification settings - Fork 1
/
113_Path_Sum_II.cpp
42 lines (39 loc) · 1.06 KB
/
113_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
41
42
/**
* 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>> ans;
vector<int> arr;
void rec(TreeNode* root, int sum, int sum_so_far){
if(sum_so_far + root->val == sum &&
root->left == NULL &&
root->right == NULL) {
arr.push_back(root->val);
ans.push_back(arr);
arr.pop_back();
return;
}
if(root->left != NULL){
arr.push_back(root->val);
rec(root->left, sum, sum_so_far + (root->val));
arr.pop_back();
}
if(root->right != NULL){
arr.push_back(root->val);
rec(root->right, sum, sum_so_far + (root->val) );
arr.pop_back();
}
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(root == NULL) return ans;
rec(root, sum, 0);
return ans;
}
};