-
Notifications
You must be signed in to change notification settings - Fork 2
/
113. Path Sum II.cpp
137 lines (84 loc) · 2.85 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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
Given the root of a binary tree and an integer targetSum,
return all root-to-leaf paths where each path's sum equals targetSum.
A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
Example 2:
Input: root = [1,2,3], targetSum = 5
Output: []
Example 3:
Input: root = [1,2], targetSum = 0
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 5000].
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
/**
* 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:
void solve(int sum, int target, TreeNode *root, vector<int> &path, vector<vector<int>> &res) {
if (!root) return;
path.push_back(root->val);
if (root->left == NULL && root->right == NULL && sum + root->val == target) {
res.push_back(path);
path.pop_back();
return;
}
solve(sum + root->val, target, root->left, path, res);
solve(sum + root->val, target, root->right, path, res);
path.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int target) {
vector<vector<int>> res;
vector<int> path;
solve(0, target, root, path, res);
return res;
}
};
/**
* 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:
void solve(int sum, int target, TreeNode *root, vector<int> &path, vector<vector<int>> &res) {
if (!root) return;
path.push_back(root->val);
if (root->left == NULL && root->right == NULL && sum + root->val == target) {
res.push_back(path);
return;
}
if (root->left) {
solve(sum + root->val, target, root->left, path, res);
path.pop_back();
}
if (root->right) {
solve(sum + root->val, target, root->right, path, res);
path.pop_back();
}
}
vector<vector<int>> pathSum(TreeNode* root, int target) {
vector<vector<int>> res;
vector<int> path;
solve(0, target, root, path, res);
return res;
}
};