Skip to content

Commit e967ff5

Browse files
refactor 113
1 parent d4c06fc commit e967ff5

File tree

1 file changed

+24
-45
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+24
-45
lines changed

src/main/java/com/fishercoder/solutions/_113.java

Lines changed: 24 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -5,54 +5,33 @@
55
import java.util.ArrayList;
66
import java.util.List;
77

8-
/**
9-
* 113. Path Sum II
10-
11-
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
12-
13-
For example:
14-
Given the below binary tree and sum = 22,
15-
5
16-
/ \
17-
4 8
18-
/ / \
19-
11 13 4
20-
/ \ / \
21-
7 2 5 1
22-
23-
return
24-
[
25-
[5,4,11,2],
26-
[5,8,4,5]
27-
]
28-
*/
298
public class _113 {
309

31-
public static class Solution1 {
32-
public List<List<Integer>> pathSum(TreeNode root, int sum) {
33-
List<List<Integer>> allPaths = new ArrayList();
34-
if (root == null) {
35-
return allPaths;
36-
}
37-
dfs(root, new ArrayList(), allPaths, sum);
38-
return allPaths;
39-
}
10+
public static class Solution1 {
11+
public List<List<Integer>> pathSum(TreeNode root, int sum) {
12+
List<List<Integer>> allPaths = new ArrayList();
13+
if (root == null) {
14+
return allPaths;
15+
}
16+
dfs(root, new ArrayList(), allPaths, sum);
17+
return allPaths;
18+
}
4019

41-
private void dfs(TreeNode root, List<Integer> path, List<List<Integer>> allPaths, int sum) {
42-
path.add(root.val);
43-
if (root.left != null) {
44-
dfs(root.left, path, allPaths, sum - root.val);
45-
}
46-
if (root.right != null) {
47-
dfs(root.right, path, allPaths, sum - root.val);
48-
}
49-
if (root.left == null && root.right == null) {
50-
/**Check if sum equals root.val, not sum equals zero!*/
51-
if (sum == root.val) {
52-
allPaths.add(new ArrayList(path));
20+
private void dfs(TreeNode root, List<Integer> path, List<List<Integer>> allPaths, int sum) {
21+
path.add(root.val);
22+
if (root.left != null) {
23+
dfs(root.left, path, allPaths, sum - root.val);
24+
}
25+
if (root.right != null) {
26+
dfs(root.right, path, allPaths, sum - root.val);
27+
}
28+
if (root.left == null && root.right == null) {
29+
/**Check if sum equals root.val, not sum equals zero!*/
30+
if (sum == root.val) {
31+
allPaths.add(new ArrayList(path));
32+
}
33+
}
34+
path.remove(path.size() - 1);
5335
}
54-
}
55-
path.remove(path.size() - 1);
5636
}
57-
}
5837
}

0 commit comments

Comments
 (0)