forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_1161.java
38 lines (35 loc) · 1.13 KB
/
_1161.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
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
import java.util.TreeMap;
public class _1161 {
public static class Solution1 {
public int maxLevelSum(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
TreeMap<Integer, Integer> treeMap = new TreeMap<>((a, b) -> b - a);
int level = 1;
while (!q.isEmpty()) {
int size = q.size();
int sum = 0;
for (int i = 0; i < size; i++) {
TreeNode curr = q.poll();
sum += curr.val;
if (curr.left != null) {
q.offer(curr.left);
}
if (curr.right != null) {
q.offer(curr.right);
}
}
treeMap.put(sum, level);
level++;
}
return treeMap.firstEntry().getValue();
}
}
}