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 31 32 33 34 35 36
|
class Solution { int ans, target; Map<Long, Integer> map;
public int pathSum(TreeNode root, int targetSum) { if (root == null) return 0; this.target = targetSum; map = new HashMap<>(); map.put(0L, 1); dfs(root, root.val); return ans; }
private void dfs(TreeNode node, long val) { if (map.containsKey(val - target)) ans += map.get(val - target); map.merge(val, 1, Integer::sum); if (node.left != null) dfs(node.left, node.left.val + val); if (node.right != null) dfs(node.right, node.right.val + val); map.put(val, map.getOrDefault(val, 0) - 1); } }
|