Leetcode437. 路径总和 III
/**
* 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:
typedef long long LL;
int cnt=0;
unordered_map<LL,LL> hash;
int pathSum(TreeNode* root, int targetSum) {
hash[0]=1;
dfs(root,targetSum,0);
return cnt;
}
void dfs(TreeNode* u,int tar,LL s)
{
if(!u) return;
s+=u->val;
cnt+=hash[s-tar];
hash[s]++;
dfs(u->left,tar,s);
dfs(u->right,tar,s);
hash[s]--;
}
};
有帮助的话可以点个赞,我会很开心的~