230. Kth Smallest Element in a BST
2016-03-21 10:38
435 查看
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?
Show Hint
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
统计左子树数量……左子树节点已知后直接在左子树找or在右子树迭代
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?
Show Hint
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
统计左子树数量……左子树节点已知后直接在左子树找or在右子树迭代
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ // 在二叉搜索树种,找到第K个元素。 // 算法如下: // 1、计算左子树元素个数left。 // 2、 left+1 = K,则根节点即为第K个元素 // left >=k, 则第K个元素在左子树中, // left +1 <k, 则转换为在右子树中,寻找第K-left-1元素。 public class Solution { private int calSize(TreeNode root){ if(root==null)return 0; return calSize(root.left)+calSize(root.right)+1; } public int kthSmallest(TreeNode root, int k) { if(root==null)return 0; int left = calSize(root.left); if(left+1==k)return root.val; if(left>=k)return kthSmallest(root.left,k); else return kthSmallest(root.right,k-left-1); } }
相关文章推荐
- Android Design Support Library 兼容库使用详解
- Ruby学习笔记1(变量,类等)
- MySQL安装
- ScrollView的滑动监听
- android AMS中主要的四个函数的作用
- 141. Linked List Cycle
- 子元素浮动之后如何撑开父元素
- Qt学习之QListWidget删除Item
- Hbuilder新建手机APP示例
- 如何输出异常栈的信息到字符串上面
- Hive学习之一 《Hive的介绍和安装》
- LinkedList 注意事项
- [转]Extjs combo数据绑定与获取
- Linux基础(一)
- 35. Search Insert Position
- Json数据中时间Date转换
- Android FragmentManage FragmentTransaction介绍
- Java虚拟机学习 - 类加载机制
- pthread_mutex_t and pthread_cond 混合使用
- weblogic中删除自动部署项目