-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2583.cpp
More file actions
24 lines (20 loc) · 686 Bytes
/
Copy path2583.cpp
File metadata and controls
24 lines (20 loc) · 686 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
class Solution {
public:
long long kthLargestLevelSum(const TreeNode *root, int k) const {
priority_queue<long long, vector<long long>, greater<>> pq;
queue<const TreeNode *> q;
for (q.emplace(root); !q.empty();) {
long long sum = 0;
for (int k = size(q); k > 0; k--) {
const auto root = q.front();
q.pop();
sum += root->val;
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
}
pq.emplace(sum);
if (size(pq) > k) pq.pop();
}
return size(pq) == k ? pq.top() : -1;
}
};