LeetCode 230: Kth Smallest Element in a BST
来源:互联网 发布:返利网如何解绑淘宝号 编辑:程序博客网 时间:2024/05/16 01:34
Given a binary search tree, write a function kthSmallest
to find thekth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
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?
在二叉搜索树种,找到第K个元素。
算法如下:
1、计算左子树元素个数left。
2、 left+1 = K,则根节点即为第K个元素
left >=k, 则第K个元素在左子树中,
left +1 <k, 则转换为在右子树中,寻找第K-left-1元素。
代码如下:
class Solution {public:int calcTreeSize(TreeNode* root){if (root == NULL)return 0;return 1+calcTreeSize(root->left) + calcTreeSize(root->right);}int kthSmallest(TreeNode* root, int k) {if (root == NULL)return 0;int leftSize = calcTreeSize(root->left);if (k == leftSize+1){return root->val;}else if (leftSize >= k){return kthSmallest(root->left,k);}else{return kthSmallest(root->right, k-leftSize-1);}}};
4 0
- #leetcode#Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode]Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- eclipse中tomcat启动报错: java.net.SocketException: select failed
- Android网络图片三级缓存策略
- 深入解析Mac OS X & iOS操作系统
- iOS给键盘添加控制栏
- 浅谈GRE阅读机考流程
- LeetCode 230: Kth Smallest Element in a BST
- iOS ——产生随心所欲的随机数字
- 北大OJ_1010题:STAMPS
- vs2013+openGL错误
- java注解Annotation的使用实例
- C++11 常用语法
- 编写ftp上传下载时需要的jar包
- 工作一年的感想
- GCD 术语 串行 vs. 并发 同步 vs. 异步