437. 路径总和 III
树的前缀和 时间复杂度O(N)
/**
* 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> hashmap;
int dfs(TreeNode* root,int cur, int targetSum) {
int ret = 0;
if(! root){
return ret;
}
cur += root -> val;
if(hashmap[cur - targetSum]){
ret += hashmap[cur - targetSum];
}
hashmap[cur] ++;
ret += dfs(root -> left, cur, targetSum);
ret += dfs(root -> right, cur, targetSum);
hashmap[cur] --; //重点!!
return ret;
}
int pathSum(TreeNode* root, int targetSum) {
hashmap[0] = 1;
return dfs(root,0,targetSum);
}
};