LeetCode_230 Kth Smallest Element in a BST
2015-07-29 16:33
274 查看
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?
计算左子树的size
left+1 = K,则根节点即为第K个元素
left >=k, 则第K个元素在左子树中,
left +1
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?
计算左子树的size
left+1 = K,则根节点即为第K个元素
left >=k, 则第K个元素在左子树中,
left +1
public int kthSmallest(TreeNode root, int k) { if(root == null) return 0; int leftSize = calSize(root.left); if(leftSize +1==k){ return root.val; }else if(leftSize >= k) { return kthSmallest(root.left, k); }else { return kthSmallest(root.right, k-leftSize-1); } } private int calSize(TreeNode root){ if(root == null) return 0; return 1+ calSize(root.left)+calSize(root.right); }
相关文章推荐
- Java final关键字
- snnu1120: 划分数(DP计数问题)
- POJ 1201 Intervals 差分约束
- [LeetCode] Set Matrix Zeroes
- c++ bitset类用法
- Java基础——内部类
- 线段树入门
- 浅谈语言
- PHP检测当前字符编码并转码
- 线段树入门
- HDU1542 线扫描求矩形面积并
- hdu 5417 RGCDQ 2015多校联合训练赛
- hdu 5316 Magician(2015多校第三场第1题)线段树单点更新+区间合并
- 实习总结
- ThinkPHP实现递归无级分类――代码少
- 基于json-lib.jar包 创建JSONArray的四个常用方法
- Android Studio 配置
- mac 下面 you have an outdated version of /usr/bin/install_name_tool installed
- Android Studio 配置
- HDU1394——线段树——Minimum Inversion Number