您的位置:首页 > 其它

230. Kth Smallest Element in a BST

2016-03-21 10:38 435 查看
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?
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: