又是一个将连续的和转化为两个前缀和相减的题目,可以参考LeetCode 记录两个关于前缀的数组题的第一题
简而言之就是深度优先遍历过程中记录每个前缀和出现的个数,如果当前和减去target的值等于某个前缀和,那么这两个节点之间的和为target。节点访问完毕记得要回溯。
/**
* 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<long long, int> preSum;
long long currentSum=0;
int result=0;
int pathSum(TreeNode* root, int targetSum) {
preSum[0] = 1;
dfs(root, targetSum);
return result;
}
void dfs(TreeNode* root, int k) {
if (!root) return ;
currentSum += root -> val;
if (preSum.find(currentSum - k) != preSum.end()) {
result += preSum[currentSum - k];
}
preSum[currentSum] ++;
dfs(root -> left, k);
dfs(root -> right, k);
preSum[currentSum] --;
currentSum -= root->val;
if (preSum[currentSum] <= 0) preSum.erase(currentSum);
}
};