|
| 1 | +import java.util.ArrayList; |
1 | 2 | import java.util.LinkedList; |
2 | 3 | import java.util.List; |
3 | 4 |
|
4 | 5 | public class PathSumII { |
5 | 6 |
|
6 | 7 | public List<List<Integer>> pathSum(TreeNode root, int sum) { |
7 | 8 | List<List<Integer>> result = new LinkedList<>(); |
8 | | - pathSum(root, sum, result, new LinkedList<Integer>()); |
| 9 | + helper(root, sum, result, new LinkedList<>()); |
9 | 10 | return result; |
10 | 11 | } |
11 | 12 |
|
12 | | - /** |
13 | | - * 这里一定要拷贝一份链表再加到result |
14 | | - * 此时path中已经包含了root,sum中还不包含root |
15 | | - */ |
16 | | - private void pathSum(TreeNode root, int sum, List<List<Integer>> result, List<Integer> list) { |
17 | | - if (root == null) { |
| 13 | + private void helper(TreeNode node, int sum, List<List<Integer>> result, List<Integer> list) { |
| 14 | + if (node == null) { |
18 | 15 | return; |
19 | 16 | } |
20 | 17 |
|
21 | | - list.add(root.val); |
| 18 | + list.add(node.val); |
| 19 | + sum -= node.val; |
22 | 20 |
|
23 | | - if (root.left == null && root.right == null && sum == root.val) { |
24 | | - result.add(new LinkedList<>(list)); |
25 | | - return; |
26 | | - } |
27 | | - |
28 | | - if (root.left != null) { |
29 | | - pathSum(root.left, sum - root.val, result, list); |
30 | | - list.remove(list.size() - 1); |
| 21 | + if (node.left == null && node.right == null && sum == 0) { |
| 22 | + result.add(new ArrayList<>(list)); |
| 23 | + } else { |
| 24 | + helper(node.left, sum, result, list); |
| 25 | + helper(node.right, sum, result, list); |
31 | 26 | } |
32 | 27 |
|
33 | | - if (root.right != null) { |
34 | | - pathSum(root.right, sum - root.val, result, list); |
35 | | - list.remove(list.size() - 1); |
36 | | - } |
| 28 | + list.remove(list.size() - 1); |
37 | 29 | } |
38 | 30 | } |
0 commit comments