-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path113-Path Sum II.cpp
executable file
·40 lines (37 loc) · 1.17 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
/**
* 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) {
if (root == nullptr) return {};
vector<vector<int>> result;
vector<int> temp = {root->val};
pathSum(root, sum - root->val, result, temp);
return result;
}
private:
void pathSum(TreeNode* root, int sum, vector<vector<int>> &result, vector<int> &temp) {
if (root ->left == nullptr && root->right == nullptr) {
if (sum == 0)
result.push_back(temp);
return;
}
if (root->left != nullptr) {
temp.push_back(root->left->val);
pathSum(root->left, sum - root->left->val, result, temp);
temp.pop_back();
}
if (root->right != nullptr) {
temp.push_back(root->right->val);
pathSum(root->right, sum - root->right->val, result, temp);
temp.pop_back();
}
}
};