-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathPathSum2.java
More file actions
32 lines (30 loc) · 991 Bytes
/
PathSum2.java
File metadata and controls
32 lines (30 loc) · 991 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
32
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class PathSum2 {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
List<Integer> path = new ArrayList<>();
dfs(root, sum, res, path);
return res;
}
public void dfs(TreeNode root, int sum, List<List<Integer>> res, List<Integer> path) {
if (root.left == null && root.right == null && root.val == sum) {
List<Integer> p = new ArrayList<>(path);
p.add(root.val);
res.add(p);
return;
}
path.add(root.val);
if (root.left != null) dfs(root.left, sum - root.val, res, path);
if (root.right != null) dfs(root.right, sum - root.val, res, path);
path.remove(path.size() - 1);
}
}