Kth Smallest Element in a BST

时间:2024-07-08 19:06:50

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?

 /**
* 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 kthSmallest(TreeNode* root, int k) {
stack <TreeNode*> tmp_s;
TreeNode* tmp=root;
while(tmp!=NULL){
tmp_s.push(tmp);
tmp=tmp->left;
}
while(k>&&(tmp!=NULL||!tmp_s.empty())){
if(tmp==NULL){
tmp=tmp_s.top();
tmp_s.pop();
if(--k==)
return tmp->val;
tmp=tmp->right;
}
else{
while(tmp!=NULL){
tmp_s.push(tmp);
tmp=tmp->left;
}
}
}
return tmp->val;
}
};