So the idea is similar as Two sum, using HashMap to store ( key : the prefix sum, value : how many ways get to this prefix sum) , and whenever reach a node, we check if prefix sum - target exists in hashmap or not, if it does, we added up the ways of prefix sum - target into res.
For instance : in one path we have 1,2,-1,-1,2, then the prefix sum will be: 1, 3, 2, 1, 3, let's say we want to find target sum is 2, then we will have{2}, {1,2,-1}, {2,-1,-1,2} and {2}ways.
Code
//O(n^2)classSolution {publicintpathSum(TreeNode root,int sum) {if (root ==null) {return0; }returncointainsSum(root, sum)+pathSum(root.left, sum)+pathSum(root.right, sum); }privateintcointainsSum(TreeNode root,int sum) {if (root ==null) {return0; }int res =0;if (root.val== sum) { res++; } res +=cointainsSum(root.left, sum -root.val); res +=cointainsSum(root.right, sum -root.val);return res; }}
classSolution {//global variable to countint count =0;publicintpathSum(TreeNode root,int sum) {if (root ==null){return count; }//counting the frequencyMap <Integer,Integer> prefixSum =newHashMap<>();//prefix sum[0] = 0prefixSum.put(0,1);dfs(root, sum, prefixSum,0);return count; }publicvoiddfs(TreeNode root,int sum,HashMap <Integer,Integer> prefixSum,int current){if (root ==null){return; } current +=root.val; count +=prefixSum.getOrDefault(current - sum,0);prefixSum.put(current,prefixSum.getOrDefault(current,0) +1);dfs(root.left, sum, prefixSum, current);dfs(root.right, sum, prefixSum, current);//backtrack to remove the current sumprefixSum.put(current,prefixSum.get(current) -1); }}