75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

437. Path Sum III

O(N^2) Brute force

Code

class Solution {
private:
    int ans = 0;

    void findPathSum(TreeNode* root, int targetSum, long long currSum)
    {
        if (root == nullptr) return;

        // Add root's value in currSum.
        currSum += root->val;
        // if we found the sum incriment ans
        if (currSum == targetSum) ans++;
        // traverse left ans right
        findPathSum(root->left, targetSum, currSum);
        findPathSum(root->right, targetSum, currSum);
    }

public:
    int pathSum(TreeNode* root, int targetSum)
    {
        if (root == NULL) return 0;

        findPathSum(root, targetSum, 0);
        pathSum(root->left, targetSum);
        pathSum(root->right, targetSum);

        return ans;
    }
};

O(N) Optimized

Code


class Solution {
private:
    int ans = 0;
    map<int, int> mp;
    void findPathSum(TreeNode* root, long long currSum, int targetSum)
    {
        if (root == NULL) return;

        // Add root's value in currSum.
        currSum += root->val;

        // found the path
        if (mp.count(currSum - targetSum)) ans += mp[currSum - targetSum];

        // traverse all the paths by going left and right
        mp[currSum]++;
        findPathSum(root->left, currSum, targetSum);
        findPathSum(root->right, currSum, targetSum);
        mp[currSum]--;

        // erase if frequency is 0
        if (mp[currSum] == 0) mp.erase(currSum);
        return;
    }

public:
    int pathSum(TreeNode* root, int targetSum)
    {
        if (root == NULL)
            return 0;

        mp[0] = 1;
        findPathSum(root, 0, targetSum);
        return ans;
    }
};