-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC2583.java
More file actions
39 lines (36 loc) · 1018 Bytes
/
LC2583.java
File metadata and controls
39 lines (36 loc) · 1018 Bytes
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
/*
* LC2583
*/
import java.util.Queue;
import java.util.LinkedList;
import java.util.PriorityQueue;
public class LC2583 {
public static long kthLargestLevelSum(TreeNode root, int k) {
// BFS (Breadth First Search)
Queue<TreeNode> queue = new LinkedList<>();
PriorityQueue<Long> pq = new PriorityQueue<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
long sum = 0l;
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
sum += node.val;
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
pq.offer(sum);
if (pq.size() > k) {
pq.poll();
}
}
if (pq.size() < k) {
return -1;
}
return pq.peek();
}
}