Skip to main content
Lesson mode

Kth Smallest Element in a BST

Since a BST's inorder traversal visits values in sorted order, the kth smallest value is simply the kth value that traversal produces. Counting as the traversal proceeds -- and stopping the instant the count reaches k -- avoids ever needing to build the full sorted list.

tree
bst
recursion
inorder-traversal

Problem in simple words

Given a binary search tree and a number k, find the kth smallest value it contains (1st smallest, 2nd smallest, and so on).

Input: tree = 3, 1, 4, null, 2, k = 1.
Output: 1, the smallest value in the tree.

Core idea

Sorted order plus a running counter is all a 'kth smallest' question ever needs -- a BST's inorder traversal produces that sorted order for free, so just count until you reach k.

How the algorithm thinks

  1. 1

    Count this node's sorted position

    VISIT

    Inorder order is sorted order, so a running counter incremented at each visit tells you exactly which sorted position you're currently at.

    Watch: The current node's value and the running count.

  2. 2

    The counter reaches k

    FOUND

    The count-th value visited in sorted order is, by definition, the count-th smallest value in the whole tree -- no further searching is needed once this matches k.

    Watch: The matching node's value and that it equals k.

  3. 3

    Stop immediately once found

    RETURN

    Continuing to traverse after the answer is already known would only visit larger values that can't possibly still be relevant.

    Watch: Which pending recursive calls short-circuit once the result is set.

Step-by-step logic

  • -Initialize count to 0 and result to null (or 'not found yet').
  • -Recursively visit the left subtree first -- but stop immediately if result has already been set.
  • -At the current node, increment count by 1.
  • -If count now equals k, record the current node's value as the result and stop.
  • -Otherwise, recursively visit the right subtree (again stopping immediately if result gets set partway through).
  • -Once the traversal ends (naturally or via early stop), result holds the answer.

Complexity

Time O(h + k)·Space O(h)

In the best case, the traversal stops as soon as the kth value is found; it visits at most h (the tree's height) nodes just to reach the leftmost value, plus up to k nodes total before stopping.

Implementation

This is the JavaScript implementation that generates the simulator timeline.

function kthSmallest(root, k) {
  let count = 0;
  let result = null;

  function inorder(node) {
    if (node === null || result !== null) return;

    inorder(node.left);
    if (result !== null) return;

    count++;
    if (count === k) {
      result = node.val;
      return;
    }

    inorder(node.right);
  }

  inorder(root);
  return result;
}

Common mistakes

Building a full sorted array and indexing into position k - 1 instead of counting inline, which works but does the sorting and the counting as two separate steps.
Omitting the early-stop check, causing the algorithm to keep visiting (and wasting time on) the rest of the tree even after the answer is already known.
Incrementing count before recursing into the left subtree, which would count nodes in the wrong (non-sorted) order.
Predict

Pause before the next step and name the state change you expect.

Trace

Watch the active node, recursive call stack, and completed branches and match it to the highlighted code line.

Explain

Say the rule that never breaks (the invariant) out loud: what remains true before and after this step?

  • -Step 1: inorder reaches 1 first (leftmost node). count becomes 1. Since k=1, count === k -- 1 is the answer, stop immediately.
  • -(If k were 3 instead): Step 1: reach 1, count=1 (not yet 3). Step 2: reach 2, count=2 (not yet 3). Step 3: reach 3 (the root), count=3 -- matches k=3, so 3 is the answer, stop immediately without ever visiting 4.

Recursion Foundations
beginner
  • - What should this function promise to do?
  • - Where does the recursion stop?
  • - Which smaller problem can you trust?
  • - How does current work connect with the smaller answer?
Open foundation
Next step

Build the reasoning before opening the simulator

Turn the mental model into a short decision checklist, then compare it with the execution timeline.