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); } }};
阅读全文
0 0
- Binary Search:230. Kth Smallest Element in a BST
- 230.Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 一种简单的自动白平衡算法
- 数据结构学习笔记
- HDU-1505 City Game
- Javascript prototype详解(一)
- Shader学习(裁剪面)
- Binary Search:230. Kth Smallest Element in a BST
- HDU 1423 求求求求求求最长上升公共子序列
- 策略模式
- 一道简单的编程题
- Linux_1_文件—文件和目录操作
- ReactNative 样式布局小结
- Unsupervised Learning of Stereo Matching
- kafka背景及架构介绍
- Javascript prototype详解(二)