Maximum Level Sum of a Binary Tree LeetCode solution in Java

1
class Solution {
2
Map<Integer, Integer> map = new HashMap<>();
3

4
public void go(TreeNode root, int level) {
5
if (root == null) return;
6
if (map.containsKey(level)) {
7
map.put(level, map.get(level) + root.val);
8
} else {
9
map.put(level, root.val);
10
}
11

12
go(root.left, level + 1);
13
go(root.right, level + 1);
14
}
15

16
public int maxLevelSum(TreeNode root) {
17
go(root, 0);
18
int max = Integer.MIN_VALUE, ind = -1;
19
for (var i : map.entrySet()) {
20
if (max < i.getValue()) {
21
max = i.getValue();
22
ind = i.getKey();
23
}
24
}
25
return ind + 1;
26
}
27
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0