2583.cpp (686B)
1 class Solution { 2 public: 3 long long kthLargestLevelSum(const TreeNode *root, int k) const { 4 priority_queue<long long, vector<long long>, greater<>> pq; 5 queue<const TreeNode *> q; 6 7 for (q.emplace(root); !q.empty();) { 8 long long sum = 0; 9 for (int k = size(q); k > 0; k--) { 10 const auto root = q.front(); 11 q.pop(); 12 sum += root->val; 13 14 if (root->left) q.push(root->left); 15 if (root->right) q.push(root->right); 16 } 17 18 pq.emplace(sum); 19 if (size(pq) > k) pq.pop(); 20 } 21 22 return size(pq) == k ? pq.top() : -1; 23 } 24 };