我的代码:
cpp
class Solution {
public:
int res = 0;
int pathSum(TreeNode* root, int targetSum) {
if(!root)return 0;
dfs(root,targetSum);
pathSum(root->left,targetSum);
pathSum(root->right,targetSum);
return res;
}
void dfs(TreeNode*root,long long targetSum){
if(!root)return;
targetSum-=root->val;
if(targetSum==0){
res++;
}
dfs(root->left,targetSum);
dfs(root->right,targetSum);
}
};
更好的代码:
cpp
class Solution {
public:
unordered_map<long long,int> cnt;
int res = 0;
int pathSum(TreeNode* root, int targetSum) {
cnt[0] = 1;
dfs(root,targetSum,0);
return res;
}
void dfs(TreeNode*root,int targetSum,long long cur){
if(!root)return;
cur+=root->val;
res+=cnt[cur-targetSum];
cnt[cur]++;
dfs(root->left,targetSum,cur),dfs(root->right,targetSum,cur);
cnt[cur]--;
}
};
第二次这个代码刚开始写的时候:没有把cnt中key的类型从int改为long long,然后一直疑惑:dfs形参cur的类型就是int啊...........
原来cnt的key的类型也要改,因为cnt存储的是某和出现了多少次,这个和可能会溢出。