-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumLevelSumOfABinaryTree.java
More file actions
44 lines (41 loc) · 1.37 KB
/
MaximumLevelSumOfABinaryTree.java
File metadata and controls
44 lines (41 loc) · 1.37 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
import common.TreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/*
* https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/
*/
public class MaximumLevelSumOfABinaryTree {
public int maxLevelSum(TreeNode root) {
int maxSoFar = Integer.MIN_VALUE;
int maxIndex = 0;
int index = 1;
List<TreeNode> current = new ArrayList<>();
current.add(root);
while (!current.isEmpty()) {
int sum = current.stream().mapToInt(node -> node.val).sum();
if (sum > maxSoFar) {
maxSoFar = sum;
maxIndex = index;
}
index++;
current = current.stream().flatMap(treeNode -> Stream.of(treeNode.left, treeNode.right)).filter(Objects::nonNull).collect(Collectors.toList());
}
return maxIndex;
}
public static void main(String[] args) {
System.out.println(new MaximumLevelSumOfABinaryTree().maxLevelSum(
new TreeNode(
1,
new TreeNode(
7,
new TreeNode(7),
new TreeNode(-8)
),
new TreeNode(0)
)
)); // 2
}
}