forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 15
/
path-sum-iii.cpp
58 lines (53 loc) · 1.46 KB
/
path-sum-iii.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
// Time: O(n)
// Space: O(h)
/**
* 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:
int pathSum(TreeNode* root, int sum) {
unordered_map<int, int> lookup;
lookup[0] = 1;
return pathSumHelper(root, 0, sum, &lookup);
}
private:
int pathSumHelper(TreeNode* root, int curr, int sum, unordered_map<int, int> *lookup) {
if (!root) {
return 0;
}
curr += root->val;
int result = lookup->count(curr - sum) ? (*lookup)[curr - sum] : 0;
++(*lookup)[curr];
result += pathSumHelper(root->left, curr, sum, lookup) + pathSumHelper(root->right, curr, sum, lookup);
--(*lookup)[curr];
if ((*lookup)[curr] == 0) {
lookup->erase(curr);
}
return result;
}
};
// Time: O(n^2)
// Space: O(h)
class Solution2 {
public:
int pathSum(TreeNode* root, int sum) {
if (!root) {
return 0;
}
return pathSumHelper(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
}
private:
int pathSumHelper(TreeNode* root, int prev, int sum) {
if (!root) {
return 0;
}
int curr = prev + root->val;
return (curr == sum) + pathSumHelper(root->left, curr, sum) + pathSumHelper(root->right, curr, sum);
}
};