[LeetCode] Kth Smallest Element in a BST 二叉搜索树中的第K小的元素
Given a binary search tree, write a function kthSmallest
to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Example 1:
- Input: root = [3,1,4,null,2], k = 1
- 3
- / \
- 1 4
- \
- 2
- Output: 1
Example 2:
- Input: root = [5,3,6,2,4,null,null,1], k = 3
- 5
- / \
- 3 6
- / \
- 2 4
- /
- 1
- Output: 3
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
这又是一道关于二叉搜索树 Binary Search Tree 的题, LeetCode 中关于 BST 的题有 Validate Binary Search Tree, Recover Binary Search Tree, Binary Search Tree Iterator, Unique Binary Search Trees, Unique Binary Search Trees II,Convert Sorted Array to Binary Search Tree 和 Convert Sorted List to Binary Search Tree。那么这道题给的提示是让我们用 BST 的性质来解题,最重要的性质是就是左<根<右,如果用中序遍历所有的节点就会得到一个有序数组。所以解题的关键还是中序遍历啊。关于二叉树的中序遍历可以参见我之前的博客 Binary Tree Inorder Traversal,里面有很多种方法可以用,先来看一种非递归的方法,中序遍历最先遍历到的是最小的结点,只要用一个计数器,每遍历一个结点,计数器自增1,当计数器到达k时,返回当前结点值即可,参见代码如下:
解法一:
- class Solution {
- public:
- int kthSmallest(TreeNode* root, int k) {
- int cnt = ;
- stack<TreeNode*> s;
- TreeNode *p = root;
- while (p || !s.empty()) {
- while (p) {
- s.push(p);
- p = p->left;
- }
- p = s.top(); s.pop();
- ++cnt;
- if (cnt == k) return p->val;
- p = p->right;
- }
- return ;
- }
- };
当然,此题我们也可以用递归来解,还是利用中序遍历来解,代码如下:
解法二:
- class Solution {
- public:
- int kthSmallest(TreeNode* root, int k) {
- return kthSmallestDFS(root, k);
- }
- int kthSmallestDFS(TreeNode* root, int &k) {
- if (!root) return -;
- int val = kthSmallestDFS(root->left, k);
- if (k == ) return val;
- if (--k == ) return root->val;
- return kthSmallestDFS(root->right, k);
- }
- };
再来看一种分治法的思路,由于 BST 的性质,可以快速定位出第k小的元素是在左子树还是右子树,首先计算出左子树的结点个数总和 cnt,如果k小于等于左子树结点总和 cnt,说明第k小的元素在左子树中,直接对左子结点调用递归即可。如果k大于 cnt+1,说明目标值在右子树中,对右子结点调用递归函数,注意此时的k应为 k-cnt-1,应为已经减少了 cnt+1 个结点。如果k正好等于 cnt+1,说明当前结点即为所求,返回当前结点值即可,参见代码如下:
解法三:
- class Solution {
- public:
- int kthSmallest(TreeNode* root, int k) {
- int cnt = count(root->left);
- if (k <= cnt) {
- return kthSmallest(root->left, k);
- } else if (k > cnt + ) {
- return kthSmallest(root->right, k - cnt - );
- }
- return root->val;
- }
- int count(TreeNode* node) {
- if (!node) return ;
- return + count(node->left) + count(node->right);
- }
- };
这道题的 Follow up 中说假设该 BST 被修改的很频繁,而且查找第k小元素的操作也很频繁,问我们如何优化。其实最好的方法还是像上面的解法那样利用分治法来快速定位目标所在的位置,但是每个递归都遍历左子树所有结点来计算个数的操作并不高效,所以应该修改原树结点的结构,使其保存包括当前结点和其左右子树所有结点的个数,这样就可以快速得到任何左子树结点总数来快速定位目标值了。定义了新结点结构体,然后就要生成新树,还是用递归的方法生成新树,注意生成的结点的 count 值要累加其左右子结点的 count 值。然后在求第k小元素的函数中,先生成新的树,然后调用递归函数。在递归函数中,不能直接访问左子结点的 count 值,因为左子节结点不一定存在,所以要先判断,如果左子结点存在的话,那么跟上面解法的操作相同。如果不存在的话,当此时k为1的时候,直接返回当前结点值,否则就对右子结点调用递归函数,k自减1,参见代码如下:
解法四:
- // Follow up
- class Solution {
- public:
- struct MyTreeNode {
- int val;
- int count;
- MyTreeNode *left;
- MyTreeNode *right;
- MyTreeNode(int x) : val(x), count(), left(NULL), right(NULL) {}
- };
- MyTreeNode* build(TreeNode* root) {
- if (!root) return NULL;
- MyTreeNode *node = new MyTreeNode(root->val);
- node->left = build(root->left);
- node->right = build(root->right);
- if (node->left) node->count += node->left->count;
- if (node->right) node->count += node->right->count;
- return node;
- }
- int kthSmallest(TreeNode* root, int k) {
- MyTreeNode *node = build(root);
- return helper(node, k);
- }
- int helper(MyTreeNode* node, int k) {
- if (node->left) {
- int cnt = node->left->count;
- if (k <= cnt) {
- return helper(node->left, k);
- } else if (k > cnt + ) {
- return helper(node->right, k - - cnt);
- }
- return node->val;
- } else {
- if (k == ) return node->val;
- return helper(node->right, k - );
- }
- }
- };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/230
类似题目:
Second Minimum Node In a Binary Tree
参考资料:
https://leetcode.com/problems/kth-smallest-element-in-a-bst/
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Kth Smallest Element in a BST 二叉搜索树中的第K小的元素的更多相关文章
- [LeetCode] 230. Kth Smallest Element in a BST 二叉搜索树中的第K小的元素
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...
- LeetCode 230 Kth Smallest Element in a BST 二叉搜索树中的第K个元素
1.非递归解法 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * ...
- 230 Kth Smallest Element in a BST 二叉搜索树中第K小的元素
给定一个二叉搜索树,编写一个函数kthSmallest来查找其中第k个最小的元素. 注意:你可以假设k总是有效的,1≤ k ≤二叉搜索树元素个数. 进阶:如果经常修改二叉搜索树(插入/删除操作)并且你 ...
- [leetcode] 230. Kth Smallest Element in a BST 找出二叉搜索树中的第k小的元素
题目大意 https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/ 230. Kth Smallest Elem ...
- Leetcode Kth Smallest Element in a BST
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...
- [LeetCode] Insert into a Binary Search Tree 二叉搜索树中插入结点
Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert t ...
- LeetCode Kth Smallest Element in a BST(数据结构)
题意: 寻找一棵BST中的第k小的数. 思路: 递归比较方便. /** * Definition for a binary tree node. * struct TreeNode { * int v ...
- [LeetCode] Inorder Successor in BST 二叉搜索树中的中序后继节点
Given a binary search tree and a node in it, find the in-order successor of that node in the BST. No ...
- [LeetCode] 285. Inorder Successor in BST 二叉搜索树中的中序后继节点
Given a binary search tree and a node in it, find the in-order successor of that node in the BST. Th ...
随机推荐
- PHP之封装一些常用的工具类函数
分享一些PHP中常用的工具里函数: <?php /** * Created by PhpStorm. * User: Steven * Date: 2016/8/12 * Time: 14:21 ...
- FFmpeg数据结构:AVPacket解析
本文主要从以下几个方面对AVPacket做解析: AVPacket在FFmpeg中的作用 字段说明 AVPacket中的内存管理 AVPacket相关函数的说明 结合AVPacket队列说明下AVPa ...
- 使用h5的history改善ajax列表请求体验
信息比较丰富的网站通常会以分页显示,在点“下一页”时,很多网站都采用了动态请求的方式,避免页面刷新.虽然大家都是ajax,但是从一些小的细节还是 可以区分优劣.一个小的细节是能否支持浏览器“后退”和“ ...
- Lua 安全调用 metatable 的简单应用
事情的经过 我们的项目中存在好几个战斗界面,不过界面中的内容略有不同.跟同事出去吃饭的时候,他问我.我们现在的战斗界面.有很多是重复的,但是也有偶尔几个地方不太一样.我在战斗过程中驱动这些界面的时候. ...
- js正则表达式校验正数、负数、和小数:^(\-|\+)?\d+(\.\d+)?$
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- ubuntu学习的简单笔记
l vi编辑器开发步骤 A)输入 vi Hello.java B) 输入 i 插入模式. C)输入 冒号.[保存退出:wq][退出不保存:q!] l 列出当前目录的所有文件:ls 详细信息的列表:ls ...
- 随便记录下系列 - node->express
随便记录下系列 - node->express 文章用啥写?VsCode. 代码用啥写?VsCode. 编辑器下载:VsCode 一.windows下安装node.js环境: 下载地址 相比以前 ...
- CentOS 6.7 如何启用中文输入法
安装CentOS系统后,如何启用中文输入法呢?这个问题看起来简单,但对于Linux初学者来说,也可能不是一件容易的事.本文笔者和大家分享一下"CentOS 6.6 如何启用中文输入法&quo ...
- offset、client、scroll开头的属性归纳总结
HTML元素有几个offset.client.scroll开头的属性,总是让人摸不着头脑.在书中看到记下来,分享给需要的小伙伴.主要是以下几个属性: 第一组:offsetWidth,offsetHei ...
- hadoop 2.7.2 + zookeeper 高可用集群部署
一.环境说明 虚拟机:vmware 11 操作系统:Ubuntu 16.04 Hadoop版本:2.7.2 Zookeeper版本:3.4.9 二.节点部署说明 三.Hosts增加配置 sudo ge ...