题解 | #二叉树之寻找第k大#
二叉树之寻找第k大
https://www.nowcoder.com/practice/8e5f73fa3f1a407eb7d0b0d7a105805e
/**
* 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整型
*/
priority_queue<int, vector<int>, greater<int>> q;
void inorder(TreeNode* root, int k) {
if (root == nullptr) {
return;
}
if (q.size() < k) {
q.push(root->val);
} else if (root->val > q.top()){
q.pop();
q.push(root->val);
}
inorder(root->left, k);
inorder(root->right, k);
}
int kthLargest(TreeNode* root, int k) {
// write code here
inorder(root, k);
return q.top();
}
};

