1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { private int count = 0;
public int pathSum(TreeNode root, int targetSum) { if (root == null) return 0; Map<Long, Integer> sumCount = new HashMap<>(); dfs(sumCount, root, 0L, targetSum); return count; }
private void dfs(Map<Long, Integer> sumCount, TreeNode node, long currSum, int target) { currSum += node.val; long remaining = currSum - target; if (remaining == 0) { count += 1; } if (sumCount.containsKey(remaining)) { count += sumCount.get(remaining); } sumCount.put(currSum, sumCount.getOrDefault(currSum, 0) + 1); if (node.left != null) { dfs(sumCount, node.left, currSum, target); } if (node.right != null) { dfs(sumCount, node.right, currSum, target); } sumCount.put(currSum, sumCount.get(currSum) - 1); } }
|