TRT
Sign in
mediumCoreLeetCode#inorder#early exit

Kth smallest element in a BST

Find the kth smallest key in a binary search tree with an inorder traversal that stops early.

The Runtime Theory Team1 min read
Taught inBinary search treesPro — members onlyA binary search tree keeps smaller keys to the left of each node and larger keys to the right, so a search discards a whole subtree at every step. Its speed depends entirely on its height.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inroot = [3, 1, 4, null, 2], k = 1

out1

inroot = [5, 3, 6, 2, 4, null, null, 1], k = 3

out3

inroot = [2, 1, 3], k = 3

out3

Given the root of a binary search tree and an integer k, return the kth smallest key (1-indexed).

Before you code

An inorder traversal lists a BST's keys in sorted order, so the answer is the kth key it visits. There is no need to collect the rest.

Hints

  1. Traverse inorder with an explicit stack and count nodes as you pop them; stop at k.
  2. That costs O(h + k) rather than O(n).
  3. Follow-up: if the tree changes often and kth queries are frequent, store each node's subtree size. Then you can walk straight to the kth key in O(h).

Production & complexity notes

When solving Kth smallest element in a BST on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Binary search trees to reinforce the underlying pattern.

What it practices

Sorted order from inorder traversal, from Binary search trees.

Not started

Sign in to save your learning progress.

Sign in to save