← DSA
MEDIUM

Kth Smallest Element in a BST

PracticeNeetCode ↗LeetCode ↗

Given the root of a binary search tree and an integer k, return the kth smallest value among all the node values in the tree.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Initialize an empty stack and set node = root.
  2. Push every left descendant onto the stack until reaching None.
  3. Pop a node, decrement k; if k reaches 0, return that node's value.
  4. Otherwise move to node.right and repeat the left-pushing step.

Complexity

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

Code

def kthSmallest(root: TreeNode | None, k: int) -> int:
    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

Code Explanation

How the solution above works, piece by piece.

  1. Inorder traversal of a BST yields values in ascending order, so the k-th visited node is the answer.
  2. The inner loop pushes nodes while walking left, reaching the smallest unvisited value.
  3. node = stack.pop() visits the next value in sorted order; decrement k.
  4. When k hits 0, return it; otherwise continue into the right subtree.
  5. O(h + k) time: it stops early instead of traversing the whole tree. O(h) stack.

Visual Walkthrough

Running it on root = [3, 1, 4, null, 2], k = 1:

Inorder order of a BST with k = 131421234badges = inorder position (sorted order)push 3, push 1 (walk left)pop 1 → k = 1 − 1 = 0return 1
An inorder walk (left, node, right) visits a BST in sorted order, shown by the badges. The iterative version stops as soon as it has popped k nodes; for k = 1 that's the leftmost node, 1.
k-th smallest

Video Explanation

NeetCode — LeetCode 230