LeetCode 230: Kth Smallest Element in a BST
2015-10-29 10:02
429 查看
Kth Smallest Element in a BST
Given a binary search tree, write a functionkthSmallestto find the kth 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?
Hint:
Try to utilize the property of a BST.
What if you could modify the BST node’s structure?
The optimal runtime complexity is O(height of BST).
解题思路
思路一:返回中序遍历下第 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) { stack<TreeNode *> ns; TreeNode *p = root; int count = 0; while (p != NULL || !ns.empty()) { while (p != NULL) { ns.push(p); p = p->left; } if (!ns.empty()) { p = ns.top(); ns.pop(); if (++count == k) return p->val; p = p->right; } } } };
思路二:如果
TreeNode有一个属性
leftCnt记录了左子树的节点个数,则在查找时可以用二分查找,时间复杂度为 O(heightofBST)。
记当前节点为node 当node不为空时循环: 若k == node.leftCnt + 1:则返回node 否则,若k > node.leftCnt:则令k -= node.leftCnt + 1,令node = node.right 否则,node = node.left
相关文章推荐
- Search Engine XSS Worm
- 简介JavaScript中search()方法的使用
- js闭包实现按秒计数
- 向大家推荐一个收集整理正则表达式的网站
- Js&Vbs正则表达式替换重复的字符
- 限制文本框中只能输入实数或整数,其它字符无效,有劳大家了!
- 关于IE的RegExp.exec的问题
- 最严谨的校验email地址的正则表达式及各种语言对应版
- Google Map Api和GOOGLE Search Api整合实现代码
- javascript中的window.location.search方法简介
- 使用javaScript动态加载Js文件和Css文件
- 教你使用javascript简单写一个页面模板引擎
- Microsoft Search 服务无法启动 解决办法.
- 正则表达式中特殊符号及正则表达式的几种方法总结(replace,test,search)
- js通过location.search来获取页面传来的参数
- JAVA中正则表达式匹配,替换,查找,切割的方法
- MongoDB正则表达式及应用
- 深入浅出解析正则表达式-替换原则
- 正则基础之 环视 Lookaround
- 正则表达式详细介绍(下)