leetcode “113. path sum ii”

LeetCode link

first thought

  • DFS

solution

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
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> results = new ArrayList<>();
if (root != null) {
List<Integer> path = new ArrayList<>();
path.add(root.val);
this.helper(root, sum - root.val, path, results);
}
return results;
}
private void helper(TreeNode root, int sum, List<Integer> path, List<List<Integer>> results) {
if (sum == 0) {
if (root.left == null && root.right == null) { // 题目要求必须是leaf
List<Integer> temp = new ArrayList<Integer>(path);
results.add(temp);
}
return;
}
if (root.left != null) {
path.add(root.left.val);
this.helper(root.left, sum - root.left.val, path, results);
path.remove(path.size() - 1);
}
if (root.right != null) {
path.add(root.right.val);
this.helper(root.right, sum - root.right.val, path, results);
path.remove(path.size() - 1);
}
}
}

problem

wrong answer

reason

not all the inputs are positive, so the sum may be 0 during some steps, we must traverse all the paths.


modification

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
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> results = new ArrayList<>();
if (root != null) {
List<Integer> path = new ArrayList<>();
path.add(root.val);
this.helper(root, sum - root.val, path, results);
}
return results;
}
private void helper(TreeNode root, int sum, List<Integer> path, List<List<Integer>> results) {
if (sum == 0 && root.left == null && root.right == null) {
List<Integer> temp = new ArrayList<Integer>(path);
results.add(temp);
return;
}
if (root.left != null) {
path.add(root.left.val);
this.helper(root.left, sum - root.left.val, path, results);
path.remove(path.size() - 1);
}
if (root.right != null) {
path.add(root.right.val);
this.helper(root.right, sum - root.right.val, path, results);
path.remove(path.size() - 1);
}
}
}