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.
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.
Input: root = [5,3,8,1,4], k = 5 Output: 8
The 5th cheapest is the most expensive here.
1 <= k <= number of prices <= 100000 <= price <= 10^6Trees 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.
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).
I'm here to help with #331 K-th Cheapest Price. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.