Intuition
Perform a full in-order traversal to collect all values in sorted order, then return the element at index k-1.
Explanation
Brute Force
An in-order traversal of a BST visits nodes in ascending order. Collect all values into a list, then simply index into position k-1.
This always visits every node even if k is small. Time is O(n) and space is O(n) for storing the full sorted list.
Why it can be improved: We do not need the entire sorted list — we can stop as soon as we have visited k nodes.
Implementation
import java.util.*;
class Solution {
public int kthSmallest(TreeNode root, int k) {
List<Integer> values = new ArrayList<>();
inorder(root, values);
return values.get(k - 1);
}
private void inorder(TreeNode node, List<Integer> values) {
if (node == null) return;
inorder(node.left, values);
values.add(node.val);
inorder(node.right, values);
}
}