一、题目内容
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?
二、代码实现
int kthSmallest(TreeNode* root, int k) {
stack<int> vec;
std::pair<TreeNode*,int> w;
stack<pair<TreeNode*,int>> st;
TreeNode* tmp=root;
//null
if(root==NULL || k<1)
return -1;
//
bool flag=false;
while(1)
{
if((tmp->left==NULL && tmp->right==NULL)||flag)
{
vec.push(tmp->val);
if(vec.size()==k)
return vec.top();
if(!st.empty())
{
tmp=st.top().first;
flag=st.top().second;
st.pop();
}
else
break;
}
else if(tmp->left!=NULL)
{
if(tmp->right!=NULL)
{
w.first=tmp->right;
w.second=0;
st.push(w);
}
w.first=tmp;
w.second=1;
st.push(w);
tmp=tmp->left;
}
else if(tmp->right!=NULL)
{
vec.push(tmp->val);
if(vec.size()==k)
return vec.top();
tmp=tmp->right;
}
}
}