Problem:
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.
Analysis:
Solutions:
C++:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode *> node_stack;
node_stack.push(root);
TreeNode *p_cur_node = root->left;
while(p_cur_node || !node_stack.empty()) {
if(p_cur_node) {
node_stack.push(p_cur_node);
p_cur_node = p_cur_node->left;
continue;
}
if(!node_stack.empty()) {
p_cur_node = node_stack.top();
--k;
if(k == 0)
return p_cur_node->val;
node_stack.pop();
p_cur_node = p_cur_node->right;
}
}
return -1;
}
Java
:
Python: