Kth Smallest and Largest in BST
Kth Smallest and Largest in BST is a GFG problem (Medium). For a BST root and a number k, find two values: the k-th smallest and the k-th largest. It joins two practice problems, k-th Smallest in BST (Medium) and Kth Largest in BST (Easy), which are solved by the same walk.
- The tree can hold up to 10⁵ nodes and may be one long chain, so recursion depth is a real risk.
- When
kis larger than the number of nodes, the k-th smallest is reported as −1.
Sorting all values first costs O(n log n) time and O(n) memory even when k is 1. The smallest-only version is Kth Smallest Element in a BST.
- 1 <= number of nodes <= 10⁵
- 0 <= node.data <= 10⁵
- 1 <= k (the k-th smallest returns -1 when k is larger than the number of nodes)
Intuition
A BST keeps smaller values in a node's left subtree and larger values in its right subtree. So the walk left subtree, node, right subtree (inorder) meets the values in ascending order, and its k-th visit is the k-th smallest.
Swap the two sides and you get a reverse inorder traversal: right subtree, node, left subtree. It meets the values in descending order, so its k-th visit is the k-th largest element in the BST.
Both answers come from one walk with the two child pointers swapped. Because the walk stops at the k-th visit, it only touches the path down to the first value plus about k more nodes.
Asking for the value at some rank of a BST, whether counted from the bottom, from the top or at the middle, means reading its inorder sequence. Read that sequence from whichever end is closer and stop early.
Approach
Before reading on: write down the order in which a left-node-right walk visits a small BST, then ask what changes if you visit right before left. Aim for O(h + k) time and O(h) extra space.
Choose a near side and a far side
For the k-th smallest the near side is left and the far side is right; for the k-th largest they swap. One helper takes a from_largest flag, so both public methods share the same dozen lines.
Slide down the near side
From the current node, keep stepping to the near child and push every node passed onto a waiting stack. The last node pushed has nothing on its near side, so no unseen value comes before it.
Count the node on top
Pop the top of waiting and subtract one from k. When k reaches 0, this node is the k-th visit in the chosen order, so return its value at once without touching the rest of the tree.
Cross to the far side
After counting a node, move to its far child and slide again. Those values come right after the node and before every node still waiting, so the order stays sorted.
Return −1 when nodes run out
If waiting is empty and there is no current node, every value has been counted and the tree has fewer than k of them. Return −1, which cannot clash with a real value because node values are never negative.
Code in Python, C++ and Java
Common pitfalls
Recursing down a long chain
def walk(node):
if node:
walk(node.right)
...while node:
waiting.append(node)
node = node.rightInsert 1, 2, …, 10⁵ in order and the tree is a single right-leaning chain. A recursive walk for the largest value goes 10⁵ calls deep: Python stops at about 1000 with RecursionError, and C++ or Java can overflow the call stack. An explicit stack has no such limit.
Mirroring only the first move
node = node.right if from_largest else node.left ... node = node.right # after counting
node = node.left if from_largest else node.right
For the 3rd largest in the tree with root 20, children 8 and 22, and 4, 12, 10, 14 below 8, the walk counts 22, then 20, then steps right into 22 again and counts it a second time, returning 22 instead of 14. Both moves must swap sides.
Edge cases
k larger than the tree, tree [2, 1, 3] with k = 5The walk counts 1, 2 and 3, then both the stack and the current pointer are empty. The loop ends and −1 is returned.
k = 1The walk slides to the leftmost node (smallest) or the rightmost node (largest) and returns it on the first count, so it costs O(h).
k equal to the number of nodesThe k-th smallest is the largest value and the k-th largest is the smallest. The walk counts every node, which is the worst case of O(n).
Complexity
Kth Smallest and Largest in BST FAQ
Can I get the k-th largest from a k-th smallest function?
Yes. With n nodes, the k-th largest is the (n − k + 1)-th smallest; in a 7-node tree the 3rd largest is the 5th smallest. The +1 is easy to drop. The catch is that you need n first, which costs a full O(n) count unless each node stores its subtree size, so the mirrored walk is usually cheaper.
Is there a version without a stack or recursion?
Yes: reverse Morris traversal, which uses O(1) extra space. Before going right from a node, find the leftmost node of its right subtree and point that node's left link back up; follow the link later to return, then remove it. The visits come out in descending order, so count to k as usual and the tree is left unchanged.
How do I answer many rank queries on a tree that keeps changing?
Give every node a count of the nodes beneath it, itself included. To find the k-th smallest, compare k with the left child's count: go left if k is smaller, return the node if k is exactly one more, otherwise go right with k reduced. Each query costs O(h), and inserts update the sizes along their path.