K-th Fastest Finisher

Mediumdepth-first searchAlso known as Kth Smallest Element in a BST

At a city marathon, each finishing time in seconds goes into a binary search tree as the runner crosses the line: faster left, slower right. The tree is never re-sorted, so its shape depends on finishing order.

The prize table calls runners by place: the 3rd fastest, the 10th for a spot prize. The tree already keeps times in order, so there is no need to copy them out and sort.

Your task

Write kthFastest(root, k). root is a valid binary search tree. Return its k-th smallest value (k = 1 is the smallest).

All times are different, and k is between 1 and the number of nodes. Trees are shown in level order, like [9000, 8000, 9500], with null for a missing child. Your function receives real TreeNode objects with val, left and right.

kthFastest(root: TreeNode, k: int) → int

Examples

Example 1
Input
root = [9000, 8000, 9500, 7800, 8600, 9200, 9900]
k = 3
Output
8600
Why

In sorted order the times are 7800, 8000, 8600, 9000, 9200, 9500 and 9900, so the 3rd is 8600. The 3rd value in the tree layout is 9500, and that is the wrong answer.

Example 2
Input
root = [9000, 8000, 9500, 7800, 8600, 9200, 9900]
k = 7
Output
9900
Why

Place 7 of 7 is the slowest runner, which is the rightmost node. Places count from 1, so k = 7 is the last runner and not past the end.

Constraints

  • 1 ≤ number of runners ≤ 1,000
  • 1 ≤ k ≤ number of runners
  • 1 ≤ time ≤ 86,400, all different
  • The tree is a valid binary search tree, at most 500 levels deep.
Start with brute force

Collect every time into a list, sort it, and return the item at k - 1. That is O(n log n) and always visits all n runners, even when you only want the fastest.

The sort is wasted work, because the tree already stores the times in order. An in-order walk reads them in sorted order and can stop after k of them.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code