GeeksforGeeks Medium

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 k is 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.

Constraints
  • 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)
bstinorder
Open on GeeksforGeeks ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def kthSmallest(self, root, k):
▶3 return self.kth(root, k, False)
▶4 
▶5 def kthLargest(self, root, k):
▶6 return self.kth(root, k, True)
▶7 
▶8 def kth(self, root, k, from_largest):
▶9 waiting, node = [], root
▶10 while waiting or node:
▶11 while node:
▶12 waiting.append(node)
▶13 node = node.right if from_largest else node.left
▶14 node = waiting.pop()
▶15 k -= 1
▶16 if k == 0:
▶17 return node.data
▶18 node = node.left if from_largest else node.right
▶19 return -1
waitingcounted208224121014rankstart at the root 20, looking for the 3rd smallest
k left3visits still needed
waitingempty
Start at the root. The smallest values sit on the left side of every node, so the walk keeps going left first. Each node it passes is put on hold until everything to its left has been counted.
waitingcounted208224121014rankhold 20, go left to 8
k left3visits still needed
waiting20
Every value in 20's left subtree is smaller than 20, so all of them come before it in this order. Hold 20 and step left to 8.
waitingcounted208224121014rankhold 8, go left to 4
k left3visits still needed
waiting20, 8
Every value in 8's left subtree is smaller than 8, so all of them come before it in this order. Hold 8 and step left to 4.
waitingcounted208224121014rankhold 4, no left child
k left3visits still needed
waiting20, 8, 4
4 has no left child, so nothing is smaller than it among the nodes still unseen. It is the next value in ascending order.
waitingcounted208224121014rank14 is 1st smallest, no right child
k left2visits still needed
waiting20, 8
Take 4 off hold: it is visit number 1, so 2 more visits are needed. It has no right child, so the next value is the most recent node still on hold (8).
waitingcounted208224121014rank218 is 2nd smallest → cross right to 12
k left1visits still needed
waiting20
Take 8 off hold: it is visit number 2, so 1 more visit is needed. Its right subtree holds the values that come right after 8 and before anything still on hold, so the walk crosses there next.
waitingcounted208224121014rank21hold 12, go left to 10
k left1visits still needed
waiting20, 12
Every value in 12's left subtree is smaller than 12, so all of them come before it in this order. Hold 12 and step left to 10.
waitingcounted208224121014rank21hold 10, no left child
k left1visits still needed
waiting20, 12, 10
10 has no left child, so nothing is smaller than it among the nodes still unseen. It is the next value in ascending order.
waitingcounted208224121014rank21310 is the 3rd smallest → answer 10
k left0visits still needed
waiting20, 12
return10
Found it. 10 is visit number 3, and the visits arrive in ascending order, so it is the 3rd smallest value. The walk stops here; 4 nodes are never counted.
05

Common pitfalls

Recursing down a long chain

✗ Wrong
def walk(node):
    if node:
        walk(node.right)
        ...
✓ Right
while node:
    waiting.append(node)
    node = node.right

Insert 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

✗ Wrong
node = node.right if from_largest else node.left
...
node = node.right  # after counting
✓ Right
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.

06

Edge cases

k larger than the tree, tree [2, 1, 3] with k = 5

The walk counts 1, 2 and 3, then both the stack and the current pointer are empty. The loop ends and −1 is returned.

k = 1

The 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 nodes

The 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).

07

Complexity

Time
O(h + k)
Space
O(h)
Up to h nodes, where h is the height, are pushed before the first count, then each of the k counts adds amortised O(1). The stack holds at most one root-to-leaf path.
08

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.