/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int, int> mp;
int count;
int accSum;
int pathSum(TreeNode* root, int sum) {
accSum = 0;
count = 0;
mp[0] = 1;
traversal(root, sum);
return count;
}
void traversal(TreeNode* root, int sum) {
if (root == nullptr) {
return;
}
accSum += root->val;
if (mp.find(accSum - sum) != mp.end()) {
count += mp[accSum - sum];
}
mp[accSum]++;
traversal(root->left, sum);
traversal(root->right, sum);
mp[accSum]--;
accSum -= root->val;
}
};