题解 | #第k轻的牛牛#
第k轻的牛牛
https://www.nowcoder.com/practice/d3b31f055b1640d9b10de0a6f2b8e6f3
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param k int整型
* @return int整型
*/
int kthLighest(TreeNode* root, int k) {
// write code here
priority_queue<int, vector<int>, less<int>> q;
queue<TreeNode*> que;
que.push(root);
while (que.size()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* t = que.front();
que.pop();
if (q.size() < k) {
q.push(t->val);
} else if (t->val < q.top()) {
q.pop();
q.push(t->val);
}
if (t->left) que.push(t->left);
if (t->right) que.push(t->right);
}
}
return q.top();
}
};



查看12道真题和解析