-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum2.java
More file actions
31 lines (24 loc) · 822 Bytes
/
PathSum2.java
File metadata and controls
31 lines (24 loc) · 822 Bytes
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
package Trees;
import java.util.ArrayList;
import java.util.List;
public class PathSum2 {
public void ps(Node root, int target, List<List<Integer>> paths, List<Integer> path) {
if (root == null) return;
target -= root.val;
path.add(root.val);
if (root.left == null && root.right == null && target == 0) {
paths.add(path);
}
ps(root.left, target, paths, new ArrayList<>(path));
ps(root.right, target, paths, new ArrayList<>(path));
}
public List<List<Integer>> pathSum(Node root, int targetSum) {
List<List<Integer>> paths = new ArrayList<>();
List<Integer> path = new ArrayList<>();
if (root == null) {
return paths;
}
ps(root, targetSum, paths, path);
return paths;
}
}