-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKth_Largest_Sum_in_a_Binary_Tree.cpp
56 lines (50 loc) · 1.39 KB
/
Kth_Largest_Sum_in_a_Binary_Tree.cpp
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
55
56
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
long long kthLargestLevelSum(TreeNode* root, int k) {
if (!root) return -1;
priority_queue<long long, vector<long long>, greater<long long>> sumQueue;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
long long sum = 0;
while (size > 0) {
TreeNode* temp = q.front();
q.pop();
sum += temp->val;
if (temp->left) q.push(temp->left);
if (temp->right) q.push(temp->right);
size--;
}
sumQueue.push(sum);
if (sumQueue.size() > k) sumQueue.pop();
}
return sumQueue.size() < k ? -1 : sumQueue.top();
}
};
TreeNode* newNode(int val) {
return new TreeNode(val);
}
int main() {
TreeNode* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
Solution solution;
int k = 2;
cout << solution.kthLargestLevelSum(root, k) << endl;
return 0;
}