Skip to content

Commit 9593e07

Browse files
authored
Create 2583. Kth Largest Sum in a Binary Tree (#615)
2 parents 679cb42 + f296aac commit 9593e07

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
long long kthLargestLevelSum(TreeNode* root, int k) {
15+
priority_queue<long long, vector<long long>, greater<long long>>pq;
16+
if (root == NULL)
17+
return 0;
18+
19+
queue<TreeNode*> q;
20+
q.push(root);
21+
while (!q.empty()) {
22+
int size = q.size();
23+
long long sum = 0;
24+
for (int i = 0; i < size; i++) {
25+
TreeNode* node = q.front();
26+
q.pop();
27+
if (node->left)
28+
q.push(node->left);
29+
if (node->right)
30+
q.push(node->right);
31+
sum += node->val;
32+
}
33+
pq.push(sum);
34+
if(pq.size() > k)
35+
pq.pop();
36+
}
37+
if(pq.size() < k)
38+
return -1;
39+
return pq.top();
40+
}
41+
};

0 commit comments

Comments
 (0)