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?
Solution:
/**
* 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 tree_size(TreeNode* root){
if (root){
return tree_size(root->left) + tree_size(root->right) + 1;
} else {
return 0;
}
}
int kthSmallest(TreeNode* root, int k) {
if (tree_size(root->left) + 1 == k) {
return root->val;
} else if (tree_size(root->left) + 1 > k) {
return kthSmallest(root->left, k);
} else {
return kthSmallest(root->right, k-(tree_size(root->left)+1));
}
}
};