Kth Smallest Element in a BST

MediumTreesbst

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the root of a binary search tree and an integer k. Return the k-th smallest value stored in the tree, counting from 1 (so k = 1 asks for the minimum). The tree follows the usual BST rule: every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger. All values are distinct and k is always valid. An inorder traversal visits a BST in sorted order, so you can stop as soon as you have seen k nodes, giving O(h + k) time where h is the tree height.

Examples

Input: root = [3,1,4,null,2], k = 1
Output: 1
Sorted values are 1,2,3,4; the first is 1.
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Sorted values are 1,2,3,4,5,6; the third is 3.

Constraints

  • 1 <= k <= n <= 10^4 (n is the number of nodes)
  • 0 <= Node.val <= 10^4
  • All values are distinct and form a valid BST

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bst problems