K-th Fastest Finisher

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

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

The prize table wants to call up runners by place: the 3rd fastest, then the 10th fastest for a random spot prize. You are given the tree and a place k. The tree already keeps the times in order, so there should be no need to copy them all out and sort them.

Your task

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

All times are different, and k is always between 1 and the number of nodes. Trees are shown in level order, like [9000, 8000, 9500], where null marks 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 order, the times are 7800, 8000, 8600, 9000, 9200, 9500, 9900. The 3rd is 8600. Reading the tree level by level would give 9000, 8000, 9500, so the 3rd value in the tree layout (9500) is the wrong answer.

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

With 7 runners, place 7 is the slowest: the rightmost node. Places count from 1, so k = 7 is the last, 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 position k - 1. That is O(n log n) and it always visits all n runners, even when you only want the fastest.

The sort is wasted work: a binary search tree already stores the times in order, you just have to read them in the right order. An in-order walk lists them sorted for free 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