Java short prefix sum hashmap


  • 0

    I cannot understand why this is easy. It took me 35 mins to figure out this solution.

    public class Solution {
        private int count = 0;
        public int pathSum(TreeNode root, int target) {
            Map<Integer, Integer> map = new HashMap<>();
            map.put(0, 1); // for special case that starting node is root
            pathSumHelper(map, root, 0, target);
            return count;
        }
        
        private void pathSumHelper(Map<Integer, Integer> prefixSumMap, TreeNode root, int sum, int target) {
            if (root == null) {
                return;
            }
            sum += root.val;
            count += prefixSumMap.getOrDefault(sum - target, 0);
            prefixSumMap.put(sum, prefixSumMap.getOrDefault(sum, 0) + 1);
            pathSumHelper(prefixSumMap, root.left, sum, target);
            pathSumHelper(prefixSumMap, root.right, sum, target);
            prefixSumMap.put(sum, prefixSumMap.get(sum) - 1);
        }
    }
    

Log in to reply
 

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