- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1022.java
38 lines (35 loc) · 1.16 KB
/
_1022.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
packagecom.fishercoder.solutions.secondthousand;
importcom.fishercoder.common.classes.TreeNode;
importjava.util.ArrayList;
importjava.util.List;
publicclass_1022 {
publicstaticclassSolution1 {
publicintsumRootToLeaf(TreeNoderoot) {
List<List<Integer>> paths = newArrayList<>();
dfs(root, paths, newArrayList<>());
intsum = 0;
for (List<Integer> list : paths) {
intnum = 0;
for (inti : list) {
num = (num << 1) + i;
}
sum += num;
}
returnsum;
}
privatevoiddfs(TreeNoderoot, List<List<Integer>> paths, List<Integer> path) {
path.add(root.val);
if (root.left != null) {
dfs(root.left, paths, path);
path.remove(path.size() - 1);
}
if (root.right != null) {
dfs(root.right, paths, path);
path.remove(path.size() - 1);
}
if (root.left == null && root.right == null) {
paths.add(newArrayList<>(path));
}
}
}
}