您的位置:首页 > 其它

230. Kth Smallest Element in a BST

2017-02-22 23:21 260 查看

题目

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?

思路

入参的二叉树满足中序升序,递归从左到右查找第k小的节点值

代码

/**
* 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 getCount(TreeNode* node)
{
if(node == NULL)
{
return 0;
}
return 1 + getCount(node->left) + getCount(node->right);
}

int kthSmallest(TreeNode* root, int k) {
int leftCount = getCount(root->left);
//左子树个数比k多
if(leftCount >= k)
{
return kthSmallest(root->left,k);
}
else if(leftCount < k-1)
{
//第k小的在右子数
return kthSmallest(root->right,k-leftCount-1);
}
//刚好是根节点
return root->val;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode