InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Kth Smallest Element in a BST

medium Original ↗ 00:00

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 means the minimum). The BST property holds everywhere: every node’s left subtree contains only smaller values and its right subtree only larger values, and all values are distinct.

Examples

  • Input: root = [3,1,4,null,2], k = 1 → Output: 1 The sorted order of values is [1, 2, 3, 4]; the 1st smallest is 1.
  • Input: root = [5,3,6,2,4,null,null,1], k = 3 → Output: 3 Sorted order is [1, 2, 3, 4, 5, 6]; the 3rd smallest is 3.
  • Input: root = [2,1,3], k = 3 → Output: 3 Sorted order is [1, 2, 3]; the 3rd smallest is the maximum, 3.

Constraints

  • The tree has n nodes with 1 <= k <= n <= 10^4.
  • 0 <= Node.val <= 10^4.
  • An O(n) pass is fine; the interesting goal is stopping early after k nodes instead of always visiting all n.

Think about it first

Hint 1 What traversal order visits a BST's values in sorted order?
Hint 2 If an inorder traversal yields values smallest-first, you don't need the whole sorted list — you only need to count how many nodes you've visited so far.
Hint 3 Do an iterative inorder traversal with an explicit stack: push left spine, pop a node, decrement `k`; when `k` hits 0, the just-popped node is the answer.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug