my c++ code using presum


  • 0
    Z
    
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int pathSum(TreeNode* rt, int sum) {
            map<int,int> pre;
            pre[0] = 1;
            int res = 0;
            dfs(rt,0,sum,res,pre);
            return res;
        }
        void dfs(TreeNode* rt,int preSum,int target,int& res,map<int,int>& pre){
            if(rt==nullptr) return ;
            preSum+=rt->val;
            res+=pre[preSum-target];
            pre[preSum]++;
            dfs(rt->left,preSum,target,res,pre);
            dfs(rt->right,preSum,target,res,pre);
            pre[preSum]--;
        }
    };
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.