您的位置:首页 > 其它

LeetCode 230: Kth Smallest Element in a BST

2017-03-18 10:39 417 查看
Given a binary search tree, write a function
kthSmallest
to find thekth 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?

在二叉搜索树种,找到第K个元素。

算法如下:

1、计算左子树元素个数left。

2、 left+1 = K,则根节点即为第K个元素

left >=k, 则第K个元素在左子树中,

left +1 <k, 则转换为在右子树中,寻找第K-left-1元素。

代码如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//  计算左子树元素个数的函数
int calculateSize(TreeNode* root){
if(root == NULL)
return 0;
return 1 + calculateSize(root->left) + calculateSize(root->right);
}
int kthSmallest(TreeNode* root, int k) {
if (root == NULL)
return 0;
int leftSize = calculateSize(root->left);   //计算左子树的元素个数
if(k == leftSize+1) // 如果k == 左子树 + 1,那么正好的根节点,因为二叉搜索树的左子树小于根,右子树大于根
return root->val;
else if(k <= leftSize)  //left >=k, 则第K个元素在左子树中
return kthSmallest(root->left, k);
else                    //eft +1 <k, 则转换为在右子树中,寻找第K-left-1元素。
return kthSmallest(root->right, k-leftSize-1);

}
};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: