I was trying to understand the logic in the code to solve the Path Sum. This is a solved problem in Gayle Laakmann McDowell's book, though my code looks a little different.
Problem: Given a Binary Tree with each node containing an integer value, count all (downward) paths that sum to a target value.
Code:
private Map<Integer, Integer> map = new HashMap<>();
private int count = 0;
private int pathSum(BinaryTreeNode root, int tgtSum)
{
map.put(0, 1);
pathSum(root, 0, tgtSum);
return count;
}
private void pathSum(BinaryTreeNode root, int runningSum, int tgtSum)
{
if (root == null) return;
runningSum += root.data;
if (map.containsKey(runningSum - tgtSum))
{
count += map.get(runningSum - tgtSum);
}
if (map.containsKey(runningSum))
{
map.put(runningSum, map.get(runningSum) + 1);
}
else
{
map.put(runningSum, 1);
}
pathSum(root.left, runningSum, tgtSum);
pathSum(root.right, runningSum, tgtSum);
map.put(runningSum, map.get(runningSum) - 1);
}
My issue:
I (kinda) understand the logic where the the runningSum is stored in the map as the key, and the value of (runningSum - tgtSum) must have to exist as one of the keys in the map if some consecutive nodes add up to the tgtSum since that difference will be the runningSum of some other node.
What I am unable to understand is that why can't we replace
count += map.get(runningSum - tgtSum) with count++?
I tried debugging it, and I can see that in some cases if the same branch has multiple consecutive nodes adding up to the tgtSum, using count++ counts only once, whereas using the frequency stored in the map the above way gives the correct output.
Though I was able to get it right after spending time debugging, I am not able to connect this part of logic of updating the variable count with the base logic of the problem by using a map with runningSum as the key and the frequency of that running sum as the value.
Can anyone simplify and explain?