-
Notifications
You must be signed in to change notification settings - Fork 8
/
PathSumII.java
55 lines (43 loc) · 1.36 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package depthfirstsearch;
// Source : https://leetcode.com/problems/path-sum-ii/
// Id : 113
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2020-01-01
// Topic : Depth-First Search
// Level : Medium
// Other :
// Tips :
// Result : 65.46% 5.26%
import java.util.LinkedList;
import java.util.List;
public class PathSumII {
// 2ms
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans = new LinkedList<>();
List<Integer> list = new LinkedList<>();
dfs(ans, list, root, sum);
return ans;
}
private void dfs(List<List<Integer>> ans, List<Integer> list, TreeNode root, int sum) {
if (root == null)
return;
list.add(root.val);
if (root.left == null && root.right == null && sum == root.val) {
// the most important step is here.
// you must be very clear about Value passing and reference passing
// it can be confusing with recursion
ans.add(new LinkedList<Integer>(list));
}
dfs(ans, list, root.left, sum - root.val);
dfs(ans, list, root.right, sum - root.val);
list.remove(list.size() - 1);
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}