-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPathSumII.java
47 lines (39 loc) · 1.37 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
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
import java.util.ArrayList;
import java.util.List;
// https://leetcode.com/problems/path-sum-ii/
public class PathSumII {
private final TreeNode root;
private final int targetSum;
public PathSumII(TreeNode root, int targetSum) {
this.root = root;
this.targetSum = targetSum;
}
public List<List<Integer>> solution() {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
List<Integer> path = new ArrayList<>();
path.add(root.val);
dfs(root, result, path, targetSum - root.val);
return result;
}
private void dfs(TreeNode node, List<List<Integer>> paths, List<Integer> path, int sum) {
if (sum == 0 && node.left == null && node.right == null) {
List<Integer> targetPath = new ArrayList<>(path);
paths.add(targetPath);
}
if (node.left != null) {
path.add(node.left.val);
dfs(node.left, paths, path, sum - node.left.val);
path.remove(path.size() - 1);
}
if (node.right != null) {
path.add(node.right.val);
dfs(node.right, paths, path, sum - node.right.val);
path.remove(path.size() - 1);
}
}
}