Leetcode: Kth Smallest Element in a BST
2015-12-19 13:06
176 查看
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. 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).
Java Solution 1 - Inorder Traversal
We can inorder traverse the tree and get the kth smallest element. Time is O(n).
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int kthSmallest(TreeNode root, int k) { TreeNode node = root; Stack<TreeNode> st = new Stack<TreeNode>(); int counter = 0; while (!st.isEmpty() || node != null) { if (node != null) { st.push(node); node = node.left; } else { node = st.pop(); counter++; if (counter == k) return node.val; node = node.right; } } return -1; } }
Recursion method:
public class Solution { int count = 0; public int kthSmallest(TreeNode root, int k) { List<Integer> res = new ArrayList<Integer>(); res.add(null); helper(root, k, res); return res.get(0); } public void helper(TreeNode root, int k, List<Integer> res) { if (root == null) return; helper(root.left, k, res); count++; if (count == k) res.set(0, root.val); helper(root.right, k, res); } }
Java Solution 2 - Extra Data Structure
We can let each node track the order, i.e., the number of elements that are less than itself(left Subtree size). Time is O(log(n)).
当前做法是O(NlogN)
如果我们频繁的操作该树,并且频繁的调用kth函数,有什么优化方法使时间复杂度降低至O(h)?h是树的高度。根据提示,我们可以在TreeNode中加入一个rank成员,这个变量记录的是该节点的左子树中节点的个数,其实就是有多少个节点比该节点小。这样我们就可以用二叉树搜索的方法来解决这个问题了。这个添加rank的操作可以在建树的时候一起完成。
public int kthSmallest(TreeNode root, int k) { int count = countNodes(root.left); if (k <= count) { return kthSmallest(root.left, k); } else if (k > count + 1) { return kthSmallest(root.right, k-1-count); // 1 is counted as current node } return root.val; } public int countNodes(TreeNode n) { if (n == null) return 0; return 1 + countNodes(n.left) + countNodes(n.right); }
相关文章推荐
- atoi和itoa之坑------还是用stringstream吧!
- 大型网站架构演化历程
- 关于追女生的一些感想 2
- MAC双系统U盘安装方法
- bzoj1030(AC自动机)
- swift学习日记(九) 自动引用计数 可选链
- Keil MDK之RTX任务管理 初始化 创建 删除
- SVN客户端(tortoisesvn)使用及studio上传下载
- service mysql start出错,mysql启动不了,解决mysql: unrecognized service错误
- PHPExcel冻结(锁定)表头的使用方法
- openoffice 安装
- Ext.js5带工具条,按钮的表格(没有行为操作)(getReferences)(16)
- Android设计模式之观察者模式
- mybatis开发DAO的2种方法
- iOS---UISwitch控件
- cordova(phonegap) 微信以及QQ分享插件
- Android设计模式之观察者模式
- 单例的实现与使用
- 【Java EE 学习 76 下】【数据采集系统第八天】【通过AOP实现日志管理】【日志管理功能分析和初步实现】
- 关于JAVA中Vector类的说明