Find k-th Smallest Element in BST

medium

Given the root of a binary search tree and an integer k (1 <= k <= number of nodes), return the k-th smallest value in the BST.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

An inorder traversal of a BST yields values in ascending order.
So the k-th smallest is the k-th node you visit inorder.
Use an iterative inorder and stop as soon as you've popped k nodes.

Common doubts

Inorder visits the left subtree (all smaller), then the node, then the right subtree (all larger) — recursively, that's ascending order.
It stops after k pops, so for small k it touches far fewer than n nodes.
Do a reverse inorder (right, node, left) and stop at the k-th pop.

Interview follow-ups

Augment each node with its subtree size; then kth is an O(height) descent using the counts.
Both rely on the inorder-is-sorted property; validate checks it's strictly increasing.

Fun facts

  • Storing subtree sizes turns kth-smallest into an order-statistics tree query in O(log n).
  • The iterative inorder here is exactly the mechanism a BST iterator exposes one value at a time.

Asked at

AmazonMicrosoftFacebook
Frequently Sometimes Occasionally
Example 1
Input: root = [5, 3, 6, 2, 4], k = 3
Output: 4
Inorder is 2, 3, 4, 5, 6; the 3rd smallest is 4.
Example 2
Input: root = [5, 3, 6, 2, 4], k = 1
Output: 2
The smallest value.
Constraints

- The number of nodes n is in the range [1, 10^4] - 1 <= k <= n - 1 <= Node.val <= 10^4 - root is a valid BST

Solve this problem →