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]--;
    }
};
posted @ 2023-07-26 11:56  穿过雾的阴霾  阅读(10)  评论(0)    收藏  举报