Given a binary search tree, write a function kthSmallest
to find thekth 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?
注意:sum在中序遍历过程中负责记录着遍历过节点总个数,当左边的树遍历完毕(相对于当前节点而言)的时候sum表示前sum-1个数(根据BST特点,左边的树的值小于当前节点的值),当前节点的值相当于第sum个数(当前节点的值总小于右边的树的值),当sum==k时,即找到了第k个数。之后的遍历也不需要了。
class Solution {
bool kthSmallest(TreeNode *root,int k,int &sum,int &res){
if(root->left&&kthSmallest(root->left,k,sum,res))
return true;
if(++sum==k){
res=root->val;
return true;
}
if(root->right&&kthSmallest(root->right,k,sum,res))
return true;
return false;
}
public:
int kthSmallest(TreeNode* root, int k) {
if(!root)
return -1;
int res;
int sum=0;
kthSmallest(root,k,sum,res);
return res;
}
};