-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPathSumII.java
40 lines (33 loc) · 1.09 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
package com.dbc;
import java.util.ArrayList;
import java.util.List;
public class PathSumII {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
private final List<List<Integer>> res = new ArrayList<>();
private void dfs(TreeNode node, List<Integer> nums, int total, int target) {
total += node.val;
nums.add(node.val);
if (node.left == null && node.right == null && total == target) this.res.add(new ArrayList<>(nums));
if (node.left != null) dfs(node.left, nums, total, target);
if (node.right != null) dfs(node.right, nums, total, target);
nums.remove(nums.size() - 1);
}
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if (root != null) dfs(root, new ArrayList<>(), 0, targetSum);
return this.res;
}
}