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.
Example 1:
Input: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3 5 / \ 3 6 / \ 2 4 / 1 Output: 3
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?
Method 1.
/**
* 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:
int kthSmallest(TreeNode* root, int k) {
int cnt = count(root->left);
if (k <= cnt)
return kthSmallest(root->left, k);
else if (k > cnt+1)
return kthSmallest(root->right, k-cnt-1);
else
return root->val;
}
int count (TreeNode* root) {
if (root == NULL)
return 0;
return count(root->left) + count(root->right) + 1;
}
};
Method 2.
/**
* 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:
int kthSmallest(TreeNode* root, int k) {
if (root == NULL)
return 0;
int cnt = 0;
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur || !st.empty()) {
while(cur) {
st.push(cur);
cur = cur->left;
}
cur = st.top();
st.pop();
cnt ++;
if (cnt == k)
return cur->val;
cur = cur->right;
}
return 0;
}
};