forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1022.java
39 lines (35 loc) · 1.15 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
39
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.List;
public class _1022 {
public static class Solution1 {
public int sumRootToLeaf(TreeNode root) {
List<List<Integer>> paths = new ArrayList<>();
dfs(root, paths, new ArrayList<>());
int sum = 0;
for (List<Integer> list : paths) {
int num = 0;
for (int i : list) {
num = (num << 1) + i;
}
sum += num;
}
return sum;
}
private void dfs(TreeNode root, 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(new ArrayList<>(path));
}
}
}
}