Kth Smallest Element in a BST
2015-08-10 22:14
351 查看
Given a binary search tree, write a function
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?
kthSmallestto 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?
public class Solution { 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); } }
相关文章推荐
- JDBC常用类和接口及增删查修
- KVC与IBOutlet和IBAction初始化
- HDU2.2.2 Joseph
- 剑指offer_面试题17_合并两个排序的链表(两种思维)
- 像素是什么意思?一个像素有多大? 告诉你像素和分辨率的关系!
- Html5(0) 初步了解
- hdu 1558 并查集+线段相交
- hdu 1856 More is better(并查集)
- hdu 1856 More is better(并查集)
- 如何判断链表中是否有环
- 【线段树】【NOI 1999】【cogs 284】内存分配
- 2015 深圳杯数模 B: DNA分子序列- RK算法
- svn造成桌面图标显示问号
- jqgrid重点总结
- JDBC及eclipse连接数据库
- 数据结构_直接插入排序法
- spring 事务的配置方式
- 快速掌握 Android Studio 中 Gradle 的使用方法
- 6.PHP 教程_PHP数据类型
- 浅析Java中的final关键字