Kth Smallest Element in a BST (LeetCode 230): Solution and Explanation

Medium
Tree
Depth First Search
Binary Search Tree
Binary Tree

Given the root of a binary search tree and an integer k, return the kth smallest value stored in the tree, counting from 1. The tree has at least k nodes, so the answer always exists.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Without using the BST property, you could collect every value, sort them, and index position k minus 1. That costs O(n log n) and throws away the most useful fact about the input: a binary search tree is already sorted, as long as you read it in the right order.

Inorder traversal visits the left subtree, then the node, then the right subtree. In a BST that produces the values in ascending order. So the kth node visited by an inorder traversal is exactly the kth smallest value. A recursive inorder that fills an array and returns arr[k - 1] is already O(n), but it still visits the whole tree even when k is 1.

An iterative inorder traversal with an explicit stack lets you stop the moment you reach the kth node. You push nodes while walking as far left as possible, because the leftmost node is the smallest. Popping a node means everything smaller than it has already been handled, so you count it. If the count reaches k you are done; otherwise you move into its right subtree, which holds the next larger values, and repeat. Only the nodes on the path to the answer plus the k visited ones are ever touched.

Approach: Iterative inorder traversal with early exit

  1. Initialize an empty stack and set curr = root.
  2. While the stack is non-empty or curr is not None, first walk left: push curr and move to curr.left until curr is None.
  3. Pop the top node. It is the smallest value not yet counted.
  4. Decrement k. If k reaches 0, return this node's value.
  5. Otherwise set curr to the popped node's right child so the next round explores the values just larger than it.

Step-by-step example

root = [3,1,4,null,2], k = 3
  1. Walk left from 3: push 3, push 1, and stop because 1 has no left child. The stack is [3, 1].
  2. Pop 1 and decrement k to 2. Move to its right child 2.
  3. Push 2. It has no left child, so pop it right away and decrement k to 1. Its right child is None.
  4. With curr None, pop 3 from the stack and decrement k to 0.
  5. Since k is 0, return 3. Node 4 is never visited.

Code: Python, Java, C++

1class Solution:
2    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
3        stack = []
4        curr = root
5        
6        while stack or curr:
7            while curr:
8                stack.append(curr)
9                curr = curr.left
10            curr = stack.pop()
11            k -= 1
12            if k == 0:
13                return curr.val
14            curr = curr.right

Time and space complexity

Time

O(h + k)

Reaching the smallest node costs up to h pushes down the left spine, and after that each of the k pops does amortized constant work. In the worst case this is O(n).

Space

O(h)

The stack holds at most one root-to-leaf path of nodes at a time, so it is bounded by the tree height h.

Other approaches

Recursive inorder into an array (time O(n), space O(n))

Traverse the whole tree inorder, append each value to a list, and return values[k - 1]. It is the easiest version to write but always visits all n nodes and stores them.

Subtree size augmentation (time O(h) per query, space O(n))

Store the size of each node's subtree. At a node, compare k with the left subtree size plus one to decide whether to return, go left, or go right with a reduced k. Building the sizes is O(n) once, but each query then takes O(h), which pays off when the tree changes often and the question is asked repeatedly.

Common mistakes

  • Decrementing k while pushing nodes rather than when popping them. Only a popped node has had all smaller values processed.
  • Forgetting to move curr to the right child after a pop, which either loops forever or skips whole subtrees.
  • Using preorder or level order. Only inorder visits a BST in sorted order.
  • Treating k as zero-based. The problem counts from 1, so the answer is the node where k hits 0 after decrementing.

Frequently asked questions

Why does inorder traversal give sorted order in a BST?

Every value in the left subtree is smaller than the node and every value in the right subtree is larger. Inorder visits left, then node, then right, so it outputs all smaller values before the node and all larger values after it.

What is the time complexity of finding the kth smallest element in a BST?

With an iterative inorder that stops early, it is O(h + k), which is O(n) in the worst case. The space is O(h) for the stack.

How would you handle frequent inserts and deletes with repeated kth smallest queries?

Store the size of each subtree in its node and keep those sizes updated during inserts and deletes. Then you can find the kth smallest by comparing k with left subtree sizes while walking down, in O(h) per query.