Java Binary Search Tree Program · OT48
Kth Smallest Element in a BST in Java
Inorder traversal visits a binary search tree in ascending order. Count the nodes as you visit them and stop at the k-th one.
Problem Statement
Given the root of a binary search tree and an integer k, return the k-th smallest value (1-indexed).
Assume 1 ≤ k ≤ the number of nodes.
Input/Output Examples
[8, 3, 10, 1, 6, null, 14, null, null, 4, 7], k = 3Output4Explanation: the ascending order starts 1, 3, 4.same tree, k = 1Output1Explanation: the leftmost node.same tree, k = 8Output14Explanation: the tree has 8 nodes; the last is the rightmost.Visual Explanation
- Visit 1countk = 2 leftfirst in order
- Visit 3countk = 1 leftsecond
- Visit 4countk = 0third: stop
- Done6, 7, 8, 10, 14 never visited4
Stopping at the k-th node means only the path to the smallest node plus k visits are needed, not the whole tree.
Approaches
Both approaches walk the tree in order and stop at the k-th value. One uses a stack; the other recursion.
Approach 1: Iterative Inorder With Early Stop (Recommended)
Idea: run the stack-based inorder traversal and return when the k-th node is popped.
- Push nodes while moving left.
- Pop a node and decrease
k. - Return its value when
kreaches 0; otherwise go right.
Time: O(h + k) · Space: O(h).
Approach 2: Recursive Inorder With a Counter
Idea: recurse left, count the current node, recurse right, and stop all work once the counter hits zero.
- Keep a remaining counter and an answer field.
- Visit the left subtree, then the node, then the right subtree.
- When the counter reaches 0, record the answer and return.
Time: O(h + k) · Space: O(h).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Iterative Inorder With Early Stop (Recommended)
The traversal stops as soon as the answer is known.
import java.util.ArrayDeque;
import java.util.Deque;
public class KthSmallestIterative {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
// Builds a tree from level-order values, where null means "no child here"
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
java.util.Queue<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < values.length) {
TreeNode node = queue.poll();
if (i < values.length && values[i] != null) {
node.left = new TreeNode(values[i]);
queue.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
queue.add(node.right);
}
i++;
}
return root;
}
// Inorder visits a BST in ascending order, so the k-th visited node is the answer
static int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
if (--k == 0) {
return curr.val; // stop early: the rest is never visited
}
curr = curr.right;
}
throw new IllegalArgumentException("k is larger than the tree");
}
public static void main(String[] args) {
TreeNode root = build(8, 3, 10, 1, 6, null, 14, null, null, 4, 7);
for (int k : new int[] {3, 1, 8}) {
System.out.println("k=" + k + " -> " + kthSmallest(root, k));
}
}
}
k=3 -> 4 k=1 -> 1 k=8 -> 14
Time complexity: O(h + k) · Space complexity: O(h).
Approach 2: Recursive Inorder With a Counter
Shorter to write; the early returns keep it from visiting the rest of the tree.
public class KthSmallestRecursive {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
// Builds a tree from level-order values, where null means "no child here"
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
java.util.Queue<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < values.length) {
TreeNode node = queue.poll();
if (i < values.length && values[i] != null) {
node.left = new TreeNode(values[i]);
queue.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
queue.add(node.right);
}
i++;
}
return root;
}
private static int remaining;
private static int answer;
// Recursive inorder with a countdown; returns as soon as the k-th value is found
static int kthSmallest(TreeNode root, int k) {
remaining = k;
answer = Integer.MIN_VALUE;
visit(root);
return answer;
}
private static void visit(TreeNode node) {
if (node == null || remaining == 0) {
return;
}
visit(node.left);
if (remaining > 0 && --remaining == 0) {
answer = node.val;
return;
}
visit(node.right);
}
public static void main(String[] args) {
TreeNode root = build(8, 3, 10, 1, 6, null, 14, null, null, 4, 7);
for (int k : new int[] {3, 1, 8}) {
System.out.println("k=" + k + " -> " + kthSmallest(root, k));
}
}
}
k=3 -> 4 k=1 -> 1 k=8 -> 14
Time complexity: O(h + k) · Space complexity: O(h).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Iterative Inorder With Early Stop | O(h + k) | O(h) |
| Recursive Inorder With a Counter | O(h + k) | O(h) |
Here h is the tree height. The traversal walks down to the smallest node and then visits k nodes.
Interview Tips and Recommended Approach
- Use the BST order. There is no need to collect and sort all values.
- Stop early. Collecting the whole traversal first costs
O(n)time and memory. - Know the follow-up. If the tree changes often, store subtree sizes in each node for
O(h)queries. - Avoid static state in real code; pass a small counter object instead.
Recommended Approach: Iterative Inorder With Early Stop
Why: it reuses the standard iterative inorder traversal, stops at the answer and needs no recursion.