K-th Cheapest Price

Medium · Trees & BSTs · about 15 min

A shop keeps its prices in a binary search tree: keys in a left subtree are smaller, keys in a right subtree are bigger, and all prices are distinct. The tree is a level-order list: the root first, then each node's left and right child in turn, with None (Python) / null (JavaScript) for a missing child. A build(level) helper in the starter turns it into nodes with .val, .left and .right.

Return the k-th smallest price (k = 1 is the cheapest). k is always between 1 and the number of prices.

  • Up to 10,000 prices, any distinct integers.

Examples:

kth_cheapest([3, 1, 4, None, 2], 1) → 1

kth_cheapest([5, 3, 6, 2, 4, None, None, 1], 3) → 3

Hints

  • Which traversal order visits BST keys from smallest to largest?
  • Count the keys as you visit them and stop at the k-th.
  • k counts from 1, not from 0.

Learn the pattern first: the Trees & BSTs lesson.

More Trees & BSTs problems