-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path437.cpp
More file actions
38 lines (36 loc) · 870 Bytes
/
Copy path437.cpp
File metadata and controls
38 lines (36 loc) · 870 Bytes
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
class Solution {
public:
vector<int> sums;
int num;
int total;
int pathSum(TreeNode *root, int sum) {
if (!root)
return 0;
num = sum;
total = 0;
sums.clear();
sums.push_back(root->val);
if (root->val == sum)
++total;
helper(root->left);
helper(root->right);
return total;
}
void helper(TreeNode *node) {
if (!node)
return;
for (int i = 0; i < sums.size(); ++i) {
sums[i] += node->val;
if (sums[i] == num)
++total;
}
sums.push_back(node->val);
if (node->val == num)
++total;
helper(node->left);
helper(node->right);
sums.pop_back();
for (int i = 0; i < sums.size(); ++i)
sums[i] -= node->val;
}
};