Given the root of a binary search tree and an integer k (1 <= k <= number of nodes), return the k-th largest value in the BST.
The tree is given in level-order (breadth-first), using null for missing children.
Input: root = [5, 3, 6, 2, 4], k = 2 Output: 5 Descending order is 6, 5, 4, 3, 2; the 2nd largest is 5.
Input: root = [5, 3, 6, 2, 4], k = 1 Output: 6 The largest value.
- The number of nodes n is in the range [1, 10^4] - 1 <= k <= n - 1 <= Node.val <= 10^4 - root is a valid BST
If an inorder traversal of a BST is ascending, a reverse inorder (right, node, left) is descending — so the k-th largest is the k-th node of a reverse inorder walk. And you can stop after k pops instead of sorting everything.
“Is k 1-indexed?”
Yes — k = 1 is the largest value.
“Is k always valid?”
Yes — 1 <= k <= number of nodes.
Reverse inorder visits a BST in descending order, so the k-th largest is the k-th node I visit that way.
I use an iterative reverse-inorder and stop as soon as I've popped k nodes.
Worked example — BST [5, 3, 6, 2, 4], k = 2
reverse inorder (descending): 6, 5, 4, 3, 2 2nd largest = 5
Swapping the left/right visit order turns ascending into descending.
No need to traverse the whole tree for a small k.
Identical structure with left and right swapped.
| Full inorder, index from end | Reverse inorder, stop at k | |
|---|---|---|
| Idea | Sort via inorder, take n-k | Descend right-first, stop at k |
| Time | O(n) | O(height + k) |
| Space | O(n) | O(height) |
Both use the ordering; the reverse walk stops early. Full code is in the Approaches selector below.
Key takeaway
Reverse inorder (right, node, left) visits a BST descending, so the k-th largest is its k-th node. Stop after k pops — O(height + k).
reverse-inorder pop the next-largest; k -= 1 if k == 0: return that node's value