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?
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
/**
* 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 {
private:
TreeNode* kthSmallestHelper(TreeNode* root, int &k) { // k mest be (&)
if (root == NULL)
return NULL;
TreeNode *ret = NULL;
ret = kthSmallestHelper(root->left, k);
if (ret != NULL)
return ret;
k = k-1;
if (k == 0)
return root;
ret = kthSmallestHelper(root->right, k);
if (ret != NULL)
return ret;
return NULL;
}
public:
int kthSmallest(TreeNode* root, int k) {
TreeNode* targetNode = kthSmallestHelper(root, k);
return targetNode->val;
}
};