-
Notifications
You must be signed in to change notification settings - Fork 3
/
113.cpp
84 lines (83 loc) · 2.59 KB
/
113.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> out;
void traverse(TreeNode* node, vector<int> curr, int targetSum){
if (node == nullptr) return;
if (node->left == nullptr && node->right == nullptr) {
if (node->val == targetSum) {
curr.push_back(node->val);
out.push_back(curr);
curr.pop_back();
}
}
if (node->left != nullptr) {
curr.push_back(node->val);
traverse(node->left, curr, targetSum - node->val);
curr.pop_back();
}
if (node->right != nullptr){
curr.push_back(node->val);
traverse(node->right, curr, targetSum - node->val);
curr.pop_back();
}
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<int> curr;
traverse(root, curr, targetSum);
return out;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> res;
void dfs(TreeNode* node, int currentSum, int targetSum, vector<int>& path) {
if (node == nullptr) return;
if (node->left == nullptr && node->right == nullptr) {
if (currentSum == targetSum) {
res.push_back(path);
}
return;
}
if (node->left) {
path.push_back(node->left->val);
dfs(node->left, currentSum + node->left->val, targetSum, path);
path.pop_back();
}
if (node->right) {
path.push_back(node->right->val);
dfs(node->right, currentSum + node->right->val, targetSum, path);
path.pop_back();
}
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<int> path;
if (root) {
path.push_back(root->val);
dfs(root, root->val, targetSum, path);
path.pop_back();
}
return res;
}
};