-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy path437_Path_Sum_III.java
47 lines (44 loc) · 1.56 KB
/
437_Path_Sum_III.java
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
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
/*public int pathSum(TreeNode root, int sum) {
if (root != null) return findPaths(root, sum)
+ pathSum(root.left, sum)
+ pathSum(root.right, sum);
return 0;
}
private int findPaths(TreeNode root, int target) {
if (root != null) return (root.val == target? 1 : 0)
+ findPaths(root.left, target - root.val)
+ findPaths(root.right, target - root.val);
return 0;
}*/
private int result;
private HashMap<Integer, Integer> cache;
public int pathSum(TreeNode root, int sum) {
result = 0;
cache = new HashMap<Integer, Integer>();
cache.put(0, 1);
pathSumHelper(root, sum, 0);
return result;
}
// https://leetcode.com/problems/path-sum-iii/discuss/91892/Python-solution-with-detailed-explanation
private void pathSumHelper(TreeNode root, int target, int soFar) {
if (root != null) {
int complement = soFar + root.val - target;
if (cache.containsKey(complement))
result += cache.get(complement);
cache.put(soFar + root.val, cache.getOrDefault(soFar + root.val, 0) + 1);
pathSumHelper(root.left, target, soFar + root.val);
pathSumHelper(root.right, target, soFar + root.val);
cache.put(soFar + root.val, cache.get(soFar + root.val) - 1);
}
}
}