Kth smallest element in a BST
Question
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Solution
因為是 BST 的關係,用 in-order 可以保證遞增順序,所以就很簡單的把它存在 array 裡面再 return 就可以了。這邊想記錄的是在 BST 裡面做 binary search
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);
}