-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0113.cpp
73 lines (65 loc) · 1.4 KB
/
0113.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
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
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 targetSum)
{
vector<vector<int>> ans;
if (root == NULL)
return ans;
vector<int> path;
path.push_back(root->val);
preorder(root, ans, path, targetSum);
return ans;
}
void preorder(TreeNode* root, vector<vector<int>>& ans, vector<int>& path, int targetSum)
{
if (root->left == NULL && root->right == NULL)
{
int size = path.size();
int sum = 0;
for (int i = 0; i < size; i++)
{
sum += path[i];
}
if (sum == targetSum)
ans.push_back(path);
}
if (root->left != NULL)
{
path.push_back(root->left->val); // µÝ¹é
preorder(root->left, ans, path, targetSum);
path.pop_back(); // »ØËÝ
}
if (root->right != NULL)
{
path.push_back(root->right->val); // µÝ¹é
preorder(root->right, ans, path, targetSum);
path.pop_back(); // »ØËÝ
}
}
};
int main()
{
TreeNode* root = new TreeNode(1);
TreeNode* node = root;
node->left = new TreeNode(2);
node->right = new TreeNode(3);
// node->left->left = new TreeNode(4);
node->left->right = new TreeNode(5);
node->right->left = new TreeNode(4);
// node->right->right = new TreeNode(7);
Solution S;
S.pathSum(root, 8);
return 0;
}