-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode2583.java
More file actions
54 lines (50 loc) · 1.56 KB
/
LeetCode2583.java
File metadata and controls
54 lines (50 loc) · 1.56 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
45
46
47
48
49
50
51
52
53
54
import java.util.Queue;
import java.util.LinkedList;
import java.util.PriorityQueue;
import util.TreeNode;
public class LeetCode2583 {
public static void main(String[] args) {
// 输入:root = [5,8,9,2,1,3,7,4,6], k = 2
// 输出:13
System.out.println(new Solution2583()
.kthLargestLevelSum(TreeNode.buildTree(new Integer[] { 5, 8, 9, 2, 1, 3, 7, 4, 6 }), 2));
// 输入:root = [1,2,null,3], k = 1
// 输出:3
System.out.println(new Solution2583()
.kthLargestLevelSum(TreeNode.buildTree(new Integer[] { 1, 2, null, 3 }), 1));
}
}
class Solution2583 {
public long kthLargestLevelSum(TreeNode root, int k) {
PriorityQueue<Long> pq = new PriorityQueue<>();
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int size = q.size();
long sum = 0;
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
sum += node.val;
if (node.left != null) {
q.add(node.left);
}
if (node.right != null) {
q.add(node.right);
}
}
if (pq.size() < k) {
pq.add(sum);
} else {
if (pq.peek() < sum) {
pq.poll();
pq.add(sum);
}
}
}
if (pq.size() < k) {
return -1;
} else {
return pq.peek();
}
}
}