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?
这一题如果不考虑Follow up。最标准的做法应该是in order的iterative遍历。就是用一个stack的那种。bst在in order里呈现的是从小到大的顺序。所以只需要iterative遍历k个元素即可。所以最后的复杂度是时间O(k), 空间O(k)
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> nodeStk = new Stack<TreeNode>();
int count = 0;
while (root != null || !nodeStk.isEmpty()) {
if (root != null) {
nodeStk.push(root);
root = root.left;
} else {
count++;
root = nodeStk.pop();
if (count == k) {
return root.val;
}
root = root.right;
}
}
return count;
}
这一题可能的难点说不定还是在follow up上。根据hint应该是在每个节点上加多一个field,用以记录比左边大的节点数目,这样就可以通过O(h)的方式来得到kth element了。或许等之后有时间的话再自己写一下验证一下。