forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PathSumII.java
38 lines (31 loc) · 1.05 KB
/
PathSumII.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
import java.util.LinkedList;
import java.util.List;
public class PathSumII {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new LinkedList<>();
pathSum(root, sum, result, new LinkedList<Integer>());
return result;
}
/**
* 这里一定要拷贝一份链表再加到result
* 此时path中已经包含了root,sum中还不包含root
*/
private void pathSum(TreeNode root, int sum, List<List<Integer>> result, List<Integer> list) {
if (root == null) {
return;
}
list.add(root.val);
if (root.left == null && root.right == null && sum == root.val) {
result.add(new LinkedList<>(list));
return;
}
if (root.left != null) {
pathSum(root.left, sum - root.val, result, list);
list.remove(list.size() - 1);
}
if (root.right != null) {
pathSum(root.right, sum - root.val, result, list);
list.remove(list.size() - 1);
}
}
}