|
| 1 | +import java.util.HashMap; |
| 2 | + |
1 | 3 | public class PathSumIII {
|
2 | 4 |
|
3 | 5 | /**
|
@@ -47,35 +49,34 @@ private void helper(TreeNode root, int sum, int[] count) {
|
47 | 49 | helper(root.right, sum - root.val, count);
|
48 | 50 | }
|
49 | 51 |
|
50 |
| - /* 如果要给路径打出来 |
51 |
| - public List<String> pathSum(TreeNode root, int sum) { |
52 |
| - List<String> result = new LinkedList<>(); |
53 |
| - pathSum(root, sum, result, ""); |
54 |
| - return result; |
| 52 | + /** |
| 53 | + * 更优化的写法,时间复杂度O(n) |
| 54 | + * 和Two Sum较类似,都是算出从root到当前节点的和,target为两段和的差值 |
| 55 | + */ |
| 56 | + public int pathSum2(TreeNode root, int sum) { |
| 57 | + HashMap<Integer, Integer> map = new HashMap<>(); |
| 58 | + map.put(0, 1); |
| 59 | + |
| 60 | + int[] count = new int[1]; |
| 61 | + helper(root, sum, 0, map, count); |
| 62 | + return count[0]; |
55 | 63 | }
|
56 | 64 |
|
57 |
| - private void pathSum(TreeNode root, int sum, List<String> list, String path) { |
58 |
| - if (root == null) { |
| 65 | + private void helper(TreeNode node, int target, int sum, HashMap<Integer, Integer> map, int[] count) { |
| 66 | + if (node == null) { |
59 | 67 | return;
|
60 | 68 | }
|
61 | 69 |
|
62 |
| - pathSumWithRoot(root, sum, list, path); |
63 |
| -
|
64 |
| - pathSum(root.left, sum, list, ""); |
65 |
| - pathSum(root.right, sum, list, ""); |
66 |
| - } |
67 |
| -
|
68 |
| - private void pathSumWithRoot(TreeNode root, int sum, List<String> list, String path) { |
69 |
| - if (root == null) { |
70 |
| - return; |
| 70 | + sum += node.val; |
| 71 | + if (map.containsKey(sum - target)) { |
| 72 | + count[0] += map.get(sum - target); |
71 | 73 | }
|
72 | 74 |
|
73 |
| - String prefix = path.isEmpty() ? "" : path + "->"; |
| 75 | + map.put(sum, map.getOrDefault(sum, 0) + 1); |
74 | 76 |
|
75 |
| - if (root.val == sum) { |
76 |
| - list.add(prefix + root.val); |
77 |
| - } |
78 |
| - pathSumWithRoot(root.left, sum - root.val, list, prefix + root.val); |
79 |
| - pathSumWithRoot(root.right, sum - root.val, list, prefix + root.val); |
80 |
| - }*/ |
| 77 | + helper(node.left, target, sum, map, count); |
| 78 | + helper(node.right, target, sum, map, count); |
| 79 | + |
| 80 | + map.put(sum, map.getOrDefault(sum, 0) - 1); |
| 81 | + } |
81 | 82 | }
|
0 commit comments