Skip to main content
32

Kth Smallest Element in a BST

Mediumtreesbst

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:TreesRead the beginner guide

Given the root of a binary search tree and an integer k, return the k-th smallest value in the tree (counting from 1).

Understand the problem

  • In a BST, everything in a node's left subtree is smaller than it, and everything in its right subtree is larger.
  • The k-th smallest is the value you'd get at position k if you sorted all the tree's values: k = 1 is the smallest, k = 2 is the second smallest, and so on.

Example 1

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

        5
       / \
      3   6
     / \
    2   4
   /
  1

Sorted, the values are 1, 2, 3, 4, 5, 6. The 3rd one is 3.

Example 2

text
Input:  root = [3, 1, 4, null, 2], k = 1
Output: 1

k = 1 asks for the smallest value: 1.

How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child.

Constraints

  • 1 <= k <= number of nodes <= 10^4

Note

Follow-up: if the tree changes often (inserts and deletes) and you're asked for the k-th smallest often, how would you speed it up?

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Walk the BST in order (left, node, right), which visits the values from smallest to largest, and stop at the k-th one.

    The simple approach (and its cost)

    Collect all the values into an array, sort it, and return arr[k - 1]. It's correct, but it visits every node and sorts them: O(n log n), and it ignores the BST's ordering entirely.

    The key insight

    A BST already keeps its values in order: smaller on the left, larger on the right. If you visit:

    1. the left subtree first (all smaller values),
    2. then the node itself,
    3. then the right subtree (all larger values),

    you visit the values in sorted order. This is an in-order traversal. So the k-th node you visit is the k-th smallest, and you can stop right there.

    Why a stack instead of recursion? It makes stopping early easy. The stack remembers the nodes we've passed on the way down, the same way the recursion's call stack would:

    1. From the current node, go left as far as possible, pushing each node onto the stack.
    2. Pop a node: nothing smaller is left unvisited, so it's the next smallest. Count it.
    3. Move to its right child (the values just above it), and repeat.

    Step by step

    root = [5, 3, 6, 2, 4, null, null, 1], k = 3:

    ActionStack (bottom → top)Visited (count)
    go left from 5: push 5, 3, 2, 15, 3, 2, 1
    pop 1, right is empty5, 3, 21 (1)
    pop 2, right is empty5, 32 (2)
    pop 353 (3) → stop

    The answer is 3. We never touched 4, 5's right side, or 6.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(h + k), where h is the tree's height: we go down one path to the smallest value, then visit k nodes.
    • Memory: O(h) for the stack.

    Common mistakes

    • Off by one. k counts from 1. Count down k and stop when it reaches 0, or count up and stop at k.
    • Visiting right before left. That gives the values in decreasing order (k-th largest instead).
    • Traversing the whole tree when you could stop. Correct, but wastes time when k is small.

    Going deeper

    The follow-up: store in each node the size of its left subtree. At a node with leftSize smaller values below it on the left: if k <= leftSize, go left; if k === leftSize + 1, it's this node; otherwise go right with k - leftSize - 1. That's O(h) per query, like a binary search. Inserts and deletes update the sizes along their path.

    Reference solution

    js
    /**
     * @param {TreeNode | null} root
     * @param {number} k
     * @return {number}
     */
    export default function kthSmallest(root, k) {
      // In-order (left, node, right) visits a BST from smallest to largest.
      // Our own stack plays the role of recursion, so we can stop the moment we hit k.
      const stack = []
      let node = root
      while (node || stack.length > 0) {
        // 1. Go left as far as possible, remembering the path.
        while (node) {
          stack.push(node)
          node = node.left
        }
        // 2. Nothing smaller is left unvisited: this is the next smallest value.
        node = stack.pop()
        k--
        if (k === 0) return node.val
        // 3. The values just above it are in its right subtree.
        node = node.right
      }
      return -1
    }
    ts
    export default function kthSmallest(root: TreeNode | null, k: number): number {
      // In-order (left, node, right) visits a BST from smallest to largest.
      // Our own stack plays the role of recursion, so we can stop the moment we hit k.
      const stack: TreeNode[] = []
      let node = root
      while (node || stack.length > 0) {
        // 1. Go left as far as possible, remembering the path.
        while (node) {
          stack.push(node)
          node = node.left
        }
        // 2. Nothing smaller is left unvisited: this is the next smallest value.
        const current = stack.pop()!
        k--
        if (k === 0) return current.val
        // 3. The values just above it are in its right subtree.
        node = current.right
      }
      return -1
    }
    python
    def kth_smallest(root: TreeNode | None, k: int) -> int:
        # In-order (left, node, right) visits a BST from smallest to largest.
        # Our own stack plays the role of recursion, so we can stop the moment we hit k.
        stack = []
        node = root
        while node or stack:
            # 1. Go left as far as possible, remembering the path.
            while node:
                stack.append(node)
                node = node.left
            # 2. Nothing smaller is left unvisited: this is the next smallest value.
            node = stack.pop()
            k -= 1
            if k == 0:
                return node.val
            # 3. The values just above it are in its right subtree.
            node = node.right
        return -1