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?
Hint:
- Try to utilize the property of a BST.
- What if you could modify the BST node's structure?
- The optimal runtime complexity is O(height of BST).
题目的意思是对一个二叉搜索树完成一个函数查找树中第k小的元素,采用一个全局的栈来保存当前已经遍历的节点,由于要找第k小的数因此采用先序遍历的方式可以得到一个顺序的数组,因此这里也是先遍历左子树,然后根节点、右子树,不过在中途加上k值判断是否已经到第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:
stack<int> min;
void printStack()
{
while(!min.empty())
{
cout<<" dfhjk:"<<min.top()<<endl;
min.pop();
}
}
void KthSmallest1(TreeNode* root,int k,int &flag)
{
//cout<<"k:"<<k<<endl;
int n = min.size();
//cout<<"a:"<<n<<endl;
if(n == k)
{
flag = 1;
return;
}
if(root->left != NULL)
KthSmallest1(root->left,k,flag);
if(flag == 1)
return ;
min.push(root->val);
n = min.size();
//cout<<"b:"<<n<<endl;
if(n == k)
{
flag = 1;
return;
}
if(root->right != NULL)
KthSmallest1(root->right,k,flag);
if(flag == 1)
return ;
n = min.size();
//cout<<"c:"<<n<<endl;
if(n == k)
{
flag = 1;
return;
}
}
int kthSmallest(TreeNode* root, int k) {
int flag = 0;
KthSmallest1(root,k,flag);
//cout<<"out:"<<min.size()<<endl;
return min.top();
}
};