Path Sum III OR Number of paths with target sum

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.

The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

Example 1:

Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output: 3
Explanation: The paths that sum to 8 are shown.

class Solution
{
public:
    void helper(TreeNode *root, int &ans,
                map<long long int, long long int> &mp,
                           long long int sum, int &target)
    {
        if (root == NULL)
            return;
        sum += root->val;

        if (mp.find(sum - target) != mp.end())
            ans += mp[sum - target];

        mp[sum]++;

        helper(root->left, ans, mp, sum, target);
        helper(root->right, ans, mp, sum, target);

        mp[sum]--;
    }
    int pathSum(TreeNode *root, int targetSum)
    {
        map<long long int, long long int> mp;

        mp[0]++;
       
        int ans = 0;
        helper(root, ans, mp, (long long int)0, targetSum);
        return ans;
    }
};

Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree