-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaxLevelSumOfBinaryTree.java
68 lines (55 loc) · 1.9 KB
/
MaxLevelSumOfBinaryTree.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
//Return the smallest level X such that the sum of all the values of nodes at level X is maximal.
//Example:
// Input: root = [1,7,0,7,-8,null,null]
// Output: 2
// Explanation:
// Level 1 sum = 1.
// Level 2 sum = 7 + 0 = 7.
// Level 3 sum = 7 + -8 = -1.
// So we return the level with the maximum sum which is level 2.
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class MaxLevelSumOfBinaryTree {
private class QueueStoredObject {
public int level;
public TreeNode n;
public QueueStoredObject(int level, TreeNode n) {
this.level = level;
this.n = n;
}
}
public int maxLevelSum(TreeNode root) {
HashMap<Integer, Integer> levelSums = new HashMap<>();
LinkedList<QueueStoredObject> queue = new LinkedList<>();
queue.add(new QueueStoredObject(1, root));
while (!queue.isEmpty()) {
QueueStoredObject obj = queue.poll();
int level = obj.level;
TreeNode node = obj.n;
Integer existingSumOfLevel = levelSums.getOrDefault(level, 0);
levelSums.put(level, node.val + existingSumOfLevel);
if (node.left != null) {
queue.add(new QueueStoredObject(level + 1, node.left));
}
if (node.right != null) {
queue.add(new QueueStoredObject(level + 1, node.right));
}
}
return Collections.max(levelSums.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();
}
}