AlgoInsight

DSA problem

Kth Smallest Element in a BST

MediumTree Traversal - In OrderPattern: Tree Traversal - In Ordertop75AmazonMicrosoftGoogleMetaAppleUber

Given the root of a Binary Search Tree (BST) and an integer k, return the k-th smallest value among all node values. The problem is 1-indexed: k = 1 asks for the minimum.

A naive solution does a full inorder traversal into an array of size n, then returns array[k - 1]. That is correct and easy to write, but it touches every node even when k is tiny, and it allocates O(n) space.

The optimal approach takes advantage of two facts. First, inorder traversal of a BST yields values in strictly ascending order, so the k-th node visited in inorder is exactly the k-th smallest. Second, we do not need to finish the traversal: we can stop as soon as we have popped k nodes from the stack.

We therefore run an iterative inorder traversal with an explicit stack, decrementing a counter on each pop. The first time the counter hits zero, the value just popped is the answer. In the best case (small k) we touch only O(h + k) nodes; in the worst case (k near n) we still touch O(n). The stack never grows beyond the height of the tree, so the space usage is O(h).

Examples

Example 1
Input: root = [3,1,4,null,2], k = 1
Output: 1
Explanation: Inorder gives [1,2,3,4]. The 1st smallest value is 1.
Example 2
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Explanation: Inorder gives [1,2,3,4,5,6]. The 3rd smallest value is 3.
Example 3
Input: root = [3,1,4,null,2], k = 4
Output: 4
Explanation: Inorder gives [1,2,3,4]. The 4th smallest is the maximum value 4.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bsttree-traversalinorderbinary-treestack

Browse all DSA problems