Kth Smallest Element in a BST

Find the k-th smallest value in a binary search tree by visiting its values in sorted order.

Given the root of a binary search tree and a whole number k, return the k-th smallest value stored in the tree. Counting starts at 1, so k = 1 asks for the smallest value, and k is always between 1 and the number of nodes.

Example 1
Input: root = [3, 1, 4, null, 2], k = 1
Output: 1
Example 2
Input: root = [5, 3, 6, 2, 4, null, null, 1], k = 3
Output: 3
Solution

The Idea

In a sorted list, finding the third smallest value is easy: you count three from the start. A binary search tree also keeps its values in order, but spread over branches instead of along a line, so the counting is less obvious.

Take Example 2. The input [5, 3, 6, 2, 4, null, null, 1] lists the tree row by row, with null for a missing child. The top node, called the root, holds 5. Its left child is 3 and its right child is 6. Below 3 sit 2 and 4, and 2 has one left child, 1.

What makes this a binary search tree is a rule about sides. Every value in a node's left part is smaller than the node, and every value in its right part is larger. Under 5, the left part holds 3, 2, 4 and 1, all smaller, and the right part holds 6. The rule holds again at 3, with 2 and 1 on its left and 4 on its right.

So where is the 3rd smallest value? It has no fixed place. The smallest value, 1, sits at the bottom, and the root 5 is only the 5th smallest. The real question is: in what order should the nodes be visited so that the values come out sorted?

The side rule answers it. At any node, its whole left part comes before it in sorted order, and its whole right part comes after it. So visit the left part first, then the node, then the right part, and do the same inside each part. Visiting a tree in this order is called an inorder traversal. Look at the picture below.

The tree of Example 2: root 5 with children 3 and 6, 3 with children 2 and 4, and 2 with a left child 1. A small number beside each node gives its place in visit order. Visited left part, then node, then right part, the values come out as 1, 2, 3, 4, 5, 6, and with k = 3 the 3rd value is 3.

The small teal number beside each node is its place in the visit order. The walk first follows the left edge, the path 5, 3, 2, 1 that keeps taking the left child. Node 1 has nothing on its left, so it comes 1st. Then come 2 and 3, because their left parts are done.

The row labelled "values in visit order" reads 1, 2, 3, 4, 5, 6, which is sorted. With k = 3 the answer is the 3rd value visited, 3, and the walk can stop there, before it ever reaches 4, 5 or 6.

Solution Approach

Turning the inorder walk into code means settling three things: why not simply list every value first, how to remember the nodes still waiting to be visited, and how to count to k.

Listing every value first

Why not collect all the values in sorted order into a list and take the one at position k - 1? That gives the right answer, but it visits and stores all the nodes, even when k = 1 needs only the first. Counting during the walk lets it stop as soon as the k-th value appears.

Remembering the way back

On the way down the left edge to 1, the walk passes 5, 3 and 2. Each of them must be visited later, and in reverse order: 2 right after 1, then 3, then 5. The node passed last is needed first.

A stack works exactly like that: a pile where you always take off the item you put on last. In Java, an ArrayDeque serves as one, with push to put a node on top and pop to take the top one off. A recursive method would keep this pile for us, but stopping it halfway takes extra care. With our own stack, stopping is a plain return.

What comes after a node is visited? Its right part. When 3 is popped, its right child 4 is next, and the walk goes down the left edge of that part, pushing as it goes. Node 4 has no left child, so it is pushed and popped at once. When a popped node has no right child, as 1 and 2 do not, the next node is simply the top of the stack.

Counting to k

How does the walk know when to stop? Each pop gives the next value in sorted order, so subtract 1 from k on every pop and return when it reaches 0. Writing --k == 0 subtracts first and compares after, so with k = 1 the very first pop is returned.

Java Solution

The method kthSmallest works in these steps:

  1. First, create an empty stack, stack, as an ArrayDeque, and set a variable node to the root.
  2. An outer loop, while (true), visits one node per round. Inside it, a second loop walks down the left edge from node, pushing each node onto stack and moving to its left child until node is null.
  3. Pop the top of stack into node; it holds the next value in sorted order. Subtract 1 from k with --k, and if k is now 0, return node.val.
  4. Otherwise set node to its right child. If there is one, the next round walks down that right part's left edge. If it is null, the next round pushes nothing and pops straight away.

The outer loop needs no exit test, because k is never larger than the number of nodes, so the k-th pop always happens.

The main method builds each tree from its row-by-row form with a small helper, build. It runs Example 1, Example 2 with every k from 1 to 6, a tree of one node, and a chain where each node has only a left child.

Java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

public class KthSmallestElementInBST {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static int kthSmallest(TreeNode root, int k) {
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode node = root;
        while (true) {
            while (node != null) {        // go as far left as possible
                stack.push(node);
                node = node.left;
            }
            node = stack.pop();           // the next value in sorted order
            if (--k == 0) {
                return node.val;
            }
            node = node.right;            // values between this one and the next on the stack
        }
    }

    // Builds a tree from the row-by-row form, where null means a missing child.
    static TreeNode build(Integer... values) {
        if (values.length == 0 || values[0] == null) return null;
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode parent = queue.poll();
            if (values[i] != null) queue.add(parent.left = new TreeNode(values[i]));
            i++;
            if (i < values.length && values[i] != null) {
                queue.add(parent.right = new TreeNode(values[i]));
            }
            i++;
        }
        return root;
    }

    public static void main(String[] args) {
        TreeNode example1 = build(3, 1, 4, null, 2);
        System.out.println("Example 1, k = 1: " + kthSmallest(example1, 1));
        TreeNode example2 = build(5, 3, 6, 2, 4, null, null, 1);
        for (int k = 1; k <= 6; k++) {
            System.out.println("Example 2, k = " + k + ": " + kthSmallest(example2, k));
        }
        System.out.println("[7], k = 1: " + kthSmallest(build(7), 1));
        TreeNode chain = build(4, 3, null, 2, null, 1);
        System.out.println("[4, 3, null, 2, null, 1], k = 4: " + kthSmallest(chain, 4));
    }
}

Running it prints:

Output
Example 1, k = 1: 1
Example 2, k = 1: 1
Example 2, k = 2: 2
Example 2, k = 3: 3
Example 2, k = 4: 4
Example 2, k = 5: 5
Example 2, k = 6: 6
[7], k = 1: 7
[4, 3, null, 2, null, 1], k = 4: 4

The six Example 2 lines give 1, 2, 3, 4, 5 and 6 for k from 1 to 6, the same order as the row in the picture, and k = 3 gives 3 as expected. With k = 6 the method returns 6, the largest value, on the very pop that empties the stack.

The line for [7] shows that a single node is its own smallest value. The last line is the chain 4, 3, 2, 1, where each node is the left child of the one above. The second loop pushes all four nodes before the first pop, and the 4th pop returns the root, 4.

The counter is easy to get wrong by one. With k-- == 0, Java compares first and subtracts after, so the method returns the (k + 1)-th value. Run on Example 2, that version returned 4 for k = 3, and for k = 6 it popped an empty stack and threw NoSuchElementException.

Complexity

The cost depends on the height of the tree, h, which is the number of nodes on its longest path from the root down, and on k.

  • Time: O(h + k), because every node pushed is either one of the k nodes popped or still on the stack when the method returns, and the stack never holds more than h nodes.
  • Space: O(h), because the stack only holds nodes on one path from the root downward, which is about log n nodes in a balanced tree of n nodes and all n in a chain like the last test.

If the tree changes often and the question is asked many times, each node can also store how many nodes its subtree holds. A walk from the root can then skip a whole left part at once and find the k-th value in O(h). The inorder walk with a stack also appears in Trees Basics.