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?
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
/**
* 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:
void __kthSmallest(TreeNode* root, int k, int& ret, TreeNode** result){
if(!root){
return;
}
if(root->left){
__kthSmallest(root->left, k, ret, result);
}
ret++;
if(ret == k){
*result = root;
return;
}
if(root->right){
__kthSmallest(root->right, k, ret, result);
}
}
int kthSmallest(TreeNode* root, int k) {
TreeNode* result = new TreeNode(-1);
int ret = 0;
__kthSmallest(root, k, ret, &result);
return result->val;
}
};
int kthSmallest(TreeNode* root, int& k) {
if (root) {
int x = kthSmallest(root->left, k);
return !k ? x : !--k ? root->val : kthSmallest(root->right, k);
}
}