Given a binary search tree, write a functionkthSmallest
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?
Solution 1: in-order iterative
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new LinkedList<>();
TreeNode cur = root;
int count = 0;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.offerLast(cur);
cur = cur.left;
}
cur = stack.pollLast();
count++;
if (count == k) {
return cur.val;
}
cur = cur.right;
}
return -1;
}
Solution 2: in-order recursive
int count = 0;
int result = Integer.MIN_VALUE;
public int kthSmallest(TreeNode root, int k) {
traverse(root, k);
return result;
}
public void traverse(TreeNode root, int k) {
if(root == null) return;
traverse(root.left, k);
count ++;
if(count == k) result = root.val;
traverse(root.right, k);
}
Solution 3: binary search (recursive)
public int kthSmallest(TreeNode root, int k) {
int count = countNodes(root.left);
if (k <= count) {
return kthSmallest(root.left, k);
} else if (k > count + 1) {
return kthSmallest(root.right, k-1-count); // 1 is counted as current node
}
return root.val;
}
public int countNodes(TreeNode n) {
if (n == null) return 0;
return 1 + countNodes(n.left) + countNodes(n.right);
}