-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreePathSum.java
More file actions
53 lines (40 loc) · 1.61 KB
/
BinaryTreePathSum.java
File metadata and controls
53 lines (40 loc) · 1.61 KB
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
48
49
50
51
52
53
package jiuzhang.java.elementary;
//Binary Tree Path Sum
import java.util.ArrayList;
import java.util.List;
public class BinaryTreePathSum {
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
if (root == null ) {
return new ArrayList<>();
}
// if (target < root.val) {
// return new ArrayList<>();
// }
if (root.left == null && root.right == null) {
if (target == root.val) {
ArrayList<Integer> aList = new ArrayList<>();
aList.add(root.val);
List<List<Integer>> halfResult = new ArrayList<>();
halfResult.add(aList);
return halfResult;
} else {
return new ArrayList<>();
}
}
List<List<Integer>> result = new ArrayList<>(binaryTreePathSum(root.left, target - root.val));
result.addAll(binaryTreePathSum(root.right, target - root.val));
for (List<Integer> aList : result) {
aList.add(0, root.val);
}
return result;
}
// List<List<Integer>> list = new ArrayList<List<Integer>>();
// or since Java 1.7
//
// List<List<Integer>> list = new ArrayList<>();
//what after new must be a class, cannot be an interface,
// what inside <> must be a type or an Interface
// you can cast a class to one of the interfaces it implements but
// not the other way,
// ArrayList<ArrayList<Integer>> cannot be converted to List<List<Integer>>
}