题解 | #二叉树之寻找第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();
    }
};

全部评论

相关推荐

从明天开始狠狠卷JV...:叽里咕噜一大堆,不就是字典序,sort一下就搞定了。
投递京东等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务