InterviewPrepKit

Home / Coding / Trees

Kth Smallest Element in a BST

medium Original β†—
Solving tips
  • Key insight: an in-order traversal of a BST yields values in sorted order, so the k-th node visited in-order is the answer β€” no sorting needed.
  • Don't store the whole list; keep a countdown and stop the instant it hits zero for O(h + k) time, O(h) space.
  • An explicit-stack iterative in-order (push left spine, pop, decrement k, go right) makes the early exit a clean return and avoids recursion-depth issues.
  • Pitfall: decrement/count exactly when a node is visited in-order (after the left recursion, before going right); and don't assume O(log n) height β€” a skewed BST has h = n.

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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.