// 暴力解classSolution{int counter =0;publicintpathSum(TreeNode root,int targetSum){if(root ==null)return0;// Check current nodehelper(root, targetSum,0L);// Go through all the nodespathSum(root.left, targetSum);pathSum(root.right, targetSum);return counter;}privatevoidhelper(TreeNode node,int targetSum,long curSum){if(node ==null)return;// Obtain current sum
curSum +=(long) node.val;// Foundif(curSum == targetSum)++counter;helper(node.left, targetSum, curSum);helper(node.right, targetSum, curSum);}}
classSolution{publicintpathSum(TreeNode root,int targetSum){// Store prefix sumMap<Long,Integer> map =newHashMap();
map.put(0L,1);returntraverse(root, targetSum,0L, map);}privateinttraverse(TreeNode node,int targetSum,long preSum,Map<Long,Integer> map){if(node ==null)return0;// Get current prefix sum
preSum += node.val;// Check if preSum has the required valueint res = map.getOrDefault(preSum - targetSum,0);// Update prefix sum
map.put(preSum, map.getOrDefault(preSum,0)+1);
res +=traverse(node.left, targetSum, preSum, map)+traverse(node.right, targetSum, preSum, map);// Backtracking, because fall back to other nodes
map.put(preSum, map.get(preSum)-1);return res;}}