Kth Smallest Element in a BST

MediumTrees · BST · In-order Traversal🧩 Binary Search Tree & In-orderLeetCode #230 ↗Updated

Problem

You are given the root of a binary search tree and an integer k (1-indexed). Return the k-th smallest value stored in the tree, i.e. the value that would sit at position k if all values were sorted ascending.
Inputroot = [3,1,4,null,2], k = 1Output1
Input[5,3,6,2,4,null,null,1], k=3Output3

1 ≤ k ≤ n ≤ 104  ·  0 ≤ Node.val ≤ 104  ·  Follow-up: what if the BST is modified often and kthSmallest is called often?

Try it yourself

Java
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
An in-order walk of a BST visits values in sorted order, so the answer is simply the k-th node visited. Stop as soon as you reach it instead of walking the whole tree.
PatternBinary Search Tree & In-order

Instinct The tree is a BST? Its in-order walk is a sorted list and every node splits the search space - think "sorted array in tree form", not "visit everything".

Memory hack Left is less, right is more, in-order reads the sorted score - and every node lives inside a (low, high) fence set by its ancestors.

Open the Binary Search Tree & In-order guide →

Approaches

Brute ForceFull In-order into a List

Time O(n)Space O(n)

Recursively collect every value in in-order, which produces a sorted list, then return list.get(k - 1). Correct, but it visits and stores all n nodes even when k = 1.

Java
public int kthSmallest(TreeNode root, int k) {
    List<Integer> vals = new ArrayList<>();
    inorder(root, vals);
    return vals.get(k - 1);
}

private void inorder(TreeNode node, List<Integer> vals) {
    if (node == null) return;
    inorder(node.left, vals);
    vals.add(node.val);
    inorder(node.right, vals);
}

Simplest to write; wastes time and memory when k is small.

At a glance

LevelApproachTimeSpace
Brute ForceFull In-order into a ListO(n)O(n)
BetterRecursive In-order with CounterO(h + k)O(h)
OptimalIterative In-order with StackO(h + k)O(h)
Common pitfalls
  • Off-by-one: k is 1-indexed, so the list answer is get(k - 1).
  • Recursive counter without an early-return check keeps walking or overwrites the result.
  • Sorting values in a heap/array ignores the free ordering the BST already gives.
Interview tips
  • State the BST property first: in-order = sorted.
  • Quote time as O(h + k), not just O(n), to show the early exit matters.
  • Answer the follow-up with size-augmented nodes (order-statistic tree).
Pattern
BST in-order = sorted stream → rank queries, k-th element, or pairwise checks on sorted values.
My notes saved in this browser