sagelearnai

Kth Smallest Element in a BST

Difficulty: Medium · Pattern: Trees & BST · LeetCode #230

Return the k-th smallest value (1-indexed) in a binary search tree.

Examples

text
tree = [5, 3, 6, 2, 4, null, null, 1], k = 3  →  3
tree = [3, 1, 4, null, 2], k = 1              →  1

Hints

  1. Which traversal of a BST yields values in ascending order?
  2. Stop as soon as you've visited k nodes, without traversing the rest.

Approach

In-order traversal (left, node, right) of a BST visits values in increasing order. Do it iteratively with an explicit stack: push all left children, pop a node (the next smallest), decrement k, and if k == 0 return its value; otherwise continue with its right subtree. Cost O(h + k).

Complexity

Time: O(h + k). Space: O(h).

Python solution
def kthSmallest(root, k):
    stack, node = [], root
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        k -= 1
        if k == 0:
            return node.val
        node = node.right
    return -1
JavaScript solution
function kthSmallest(root, k) {
  const stack = []; let node = root;
  while (stack.length || node) {
    while (node) { stack.push(node); node = node.left; }
    node = stack.pop();
    if (--k === 0) return node.val;
    node = node.right;
  }
  return -1;
}