Advertisement
jayati

O(N) approach to Path sum 3

May 10th, 2024
753
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.66 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int get(TreeNode *root, int t, map<long long, int> &mp, long long pr = 0) {
  4.         if (root == nullptr) return 0;
  5.         pr += root->val;
  6.         int ans = mp[pr - t];
  7.         mp[pr]++;
  8.  
  9.         // Recursively calculate the count of paths for left and right subtrees
  10.         ans += get(root->left, t, mp, pr);
  11.         ans += get(root->right, t, mp, pr);
  12.  
  13.         // Decrement the frequency of the current prefix sum (backtrack)
  14.         mp[pr]--;
  15.         return ans;
  16.     }
  17.  
  18.     int pathSum(TreeNode* root, int targetSum) {
  19.         map<long long, int> mp;
  20.         mp[0] = 1;
  21.         return get(root, targetSum, mp);
  22.     }
  23. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement