题目描述:
主要思路:
方法一:递归
从每个节点开始一次递归
class Solution {
public:
int ans=0;
void dfs(TreeNode* now,int targetSum, long sum)
{
if(!now)
return;
sum+=now->val;
if(sum==targetSum)
ans+=1;
dfs(now->left,targetSum,sum);
dfs(now->right,targetSum,sum);
}
int pathSum(TreeNode* root, int targetSum) {
if(!root)
return 0;
dfs(root,targetSum,0);
pathSum(root->left,targetSum);
pathSum(root->right,targetSum);
return ans;
}
};
方法二:前缀和
利用哈希表记录前缀和,相减得到结果
class Solution {
public:
int ans;
unordered_map<long,int> book;
void dfs(TreeNode* root,int targetSum, long sum)
{
if(!root)
return;
sum+=root->val;
ans+=book[sum-targetSum];
book[sum]+=1;
dfs(root->left,targetSum,sum);
dfs(root->right,targetSum,sum);
--book[sum];
}
int pathSum(TreeNode* root, int targetSum) {
book[0]=1;
dfs(root,targetSum,0);
return ans;
}
};