Given a BST and a positive number k, find the k'th smallest node in it.

For example, the 4th smallest node in the following BST is 15, and the 6th smallest is 20. The 8th smallest node does not exist.

Kth smallest node in the BST

Practice this problem

The idea is to traverse the BST in an inorder fashion since the inorder traversal visits the nodes of a BST in the sorted order. Maintain a counter along with recursion that keeps track of the visited nodes, and when that counter reaches k, return that node.

The algorithm can be implemented as follows in C, Java, and Python. The code is optimized to visit the right subtree only when the k'th smallest is not found in the left subtree.

C


Download  Run Code

Output:

4th smallest element is 15

Java


Download  Run Code

Output:

4th smallest element is 15

Python


Download  Run Code

Output:

4th smallest element is 15

The time complexity of the above solution is O(n), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack.

 
Exercise:

1. Modify the solution to find the k'th largest node in the BST (Check solution here).

2. Modify the solution to print the first k smallest nodes in the BST (Check solution here).