-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathPath_Sum_III.cpp
More file actions
27 lines (26 loc) · 767 Bytes
/
Path_Sum_III.cpp
File metadata and controls
27 lines (26 loc) · 767 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
/**
* 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 {
int pathSumUtil(TreeNode* root, int curr, const int sum, unordered_map<int, int>& sumMap) {
if(!root) return 0;
curr += root->val;
int freq = sumMap[curr - sum];
sumMap[curr]++;
int ret = freq + pathSumUtil(root->left, curr, sum, sumMap) + pathSumUtil(root->right, curr, sum, sumMap);
sumMap[curr]--;
return ret;
}
public:
int pathSum(TreeNode* root, int sum) {
unordered_map<int, int> sumMap;
sumMap[0]++;
return pathSumUtil(root, 0, sum, sumMap);
}
};