idea like subarray sum equals k, just this one is tree style
time: O(n)
space: O(n)
classSolution {// use hash map to store map(presum, count)// presum, if map.get(presum - target) exists, retirive the count(it's the correct path)publicintpathSum(TreeNode root,int targetSum) {if (root ==null) return0;Map<Integer,Integer> map =newHashMap<>();map.put(0,1); // zero sum, 也是一個 count, 起點, 要注意, 不然有些。case 會有問題 returnhelper(root,0, targetSum, map); }privateinthelper(TreeNode node,int curSum,int targetSum,Map<Integer,Integer> map) {if (node ==null) return0; curSum +=node.val;int count =map.getOrDefault(curSum - targetSum,0);map.put(curSum,map.getOrDefault(curSum,0) +1); // try backtracking count +=helper(node.left, curSum, targetSum, map); count +=helper(node.right, curSum, targetSum, map);map.put(curSum,map.get(curSum) -1); // do backtrackingreturn count; }}
global variable
classSolution {int count =0;publicintpathSum(TreeNode root,int targetSum) {Map<Integer,Integer> map =newHashMap<>();map.put(0,1);dfs(root, targetSum, map,0);return count; }privatevoiddfs(TreeNode root,int targetSum,Map<Integer,Integer> map,int sum) {if (root ==null) {return; } sum +=root.val; // but why use same sum work? becase dfs will go back to upper level count +=map.getOrDefault(sum - targetSum,0);map.put(sum,map.getOrDefault(sum,0)+1);dfs(root.left, targetSum, map, sum);dfs(root.right, targetSum, map, sum);map.put(sum,map.get(sum) -1); // notice map backtracking }}/*find num of path sum equal to targetSummap(sum, count)ex:Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8Output: 3map(10, 1)18 - 8 find in map => count += map(10, 1)ex:Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22Output: 3 5, 4, 8, 11,null, 13,4,7,2, null,null, 5,10,15,15 4 11 2 = 22 find in (0,1)27 -22 = 5 find in (5,1)27 -22 = 5 find in (5,1)*/
dfs sum can show all the sum in a tree
privatevoiddfs(TreeNode root,int targetSum,Map<Integer, Integer> map,int sum) {if (root ==null) {return; } sum +=root.val; // but why use same sum work? becase dfs will go back to upper levelSystem.out.println(sum);