Binary Search:230. Kth Smallest Element in a BST

来源:互联网 发布:手机淘宝降价提醒 编辑:程序博客网 时间:2024/06/06 03:13

这道题是求一个二叉搜索树中的第k个数是什么。

受到Binary Search:378. Kth Smallest Element in a Sorted Matrix这个题的启发,我使用了一个最大堆,维护这个最大堆使得里面始终包含k个数,那么遍历完这个二叉树之后的最大堆,最大的那个就是第k个数。

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int kthSmallest(TreeNode* root, int k) {        priority_queue<int> q;        TreeNode* node = root;        helper(root, k, q);        return q.top();    }    void helper(TreeNode* root, int k, priority_queue<int>& q)    {        if(root != NULL)        {            q.emplace(root->val);            if(q.size() > k)            {                q.pop();            }            helper(root->left, k, q);            helper(root->right, k, q);        }    }};


原创粉丝点击