Skip to the code
cf.
+25 XP

#331 K-th Cheapest Price

medium

A shop keeps its product prices in a binary search tree: for every node, all prices in its left subtree are smaller and all prices in its right subtree are bigger. Prices are unique.

Write kthCheapest(root, k) that returns the k-th smallest price, where k = 1 means the cheapest. k is always between 1 and the number of prices. Try to stop as soon as you reach the answer.

Example 1

Input: root = [5,3,8,1,4], k = 2
Output: 3

In sorted order the prices are 1, 3, 4, 5, 8; the 2nd is 3.

Example 2

Input: root = [5,3,8,1,4], k = 5
Output: 8

The 5th cheapest is the most expensive here.

Constraints

  • 1 <= k <= number of prices <= 10000
  • 0 <= price <= 10^6

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).