Kth Largest Element in BST

medium

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.

Hints

A reverse inorder (right, node, left) visits a BST in descending order.
So the k-th largest is the k-th node of a reverse inorder walk.
Use an iterative reverse inorder and stop after k pops.

Common doubts

Visiting the right subtree (all larger) before the node before the left subtree (all smaller) yields values largest-first.
It's the exact mirror — swap every left/right in the kth-smallest solution.
For small k you only need the first k largest values, not a full sort.

Interview follow-ups

Augment nodes with subtree sizes and descend using the counts — O(log n) per query on a balanced tree.
Yes — one ascending inorder gives index k-1 (smallest) and index n-k (largest).

Fun facts

  • kth-largest and kth-smallest are the same algorithm reflected — the BST's symmetry made visible.
  • The descending walk here is a right-leaning version of the BST iterator's mechanism.

Asked at

AmazonFlipkartMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: root = [5, 3, 6, 2, 4], k = 2
Output: 5
Descending order is 6, 5, 4, 3, 2; the 2nd largest is 5.
Example 2
Input: root = [5, 3, 6, 2, 4], k = 1
Output: 6
The largest value.
Constraints

- 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

Solve this problem →