您的位置:首页 > 其它

Binary Search:230. Kth Smallest Element in a BST

2017-10-21 19:32 218 查看


这道题是求一个二叉搜索树中的第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);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: