VOOZH about

URL: https://www.geeksforgeeks.org/dsa/kth-smallest-element-in-a-perfect-binary-search-tree/

⇱ Kth Smallest element in a Perfect Binary Search Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Kth Smallest element in a Perfect Binary Search Tree

Last Updated : 15 Jul, 2025

Given a Perfect BST with N nodes and an integer K, the task is to find the Kth smallest element is present in the tree.

Example:

Input:
K = 3, N = 15
 50 
 / \ 
 30 70 
 / \ / \ 
 20 40 60 80
 /\ /\ /\ / \
 14 25 35 45 55 65 75 85 
Output: 25

Explanation: 
The 3rd smallest element
in the given BST is 25


Input: 
K = 9, N = 15
 50 
 / \ 
 30 70 
 / \ / \ 
 20 40 60 80
 /\ /\ /\ / \
 14 25 35 45 55 65 75 85 
Output: 55

Explanation: 
The 9th smallest element
in the given BST is 55

Naive Approach: Do the Inorder traversal in a perfect BST, such as morris traversal or recursive solution, which visits every node and returns the kth visit key. It takes O(N) time complexity to complete the task. 

Efficient Approach: 
Since the given BST is perfect and the number of nodes of the entire tree is already known, the computational complexity to solve the problem can be reduced to log(N). Follow the steps given below to solve the problem:

  • in a perfect BST tree(N), |N| will always be odd in a perfect binary tree, the location of the median in any perfect BST is floor(|N|/2) + 1.
  • Calculate the number of nodes in every sub-tree by dividing the total nodes as floor(|N| / 2).
  • The left sub-tree of the Perfect BST will always contain the Kth smallest element if:
    • K < location(median(N))=M this is because Mth smallest element will always be larger than the Kth smallest element and every element in the right sub-tree will be larger than the Mth smallest element
  • The right sub-tree of Perfect BST will always contain a Rth smallest element if:
    • K > location(median(N))=M, in this case, K - location(median(N))=R is the Rth smallest element in the right subtree. This is because Rth smallest element in the right sub-tree is larger than Mth smallest element and every element in the left-sub tree is smaller than Mth smallest element but Rth smallest element is larger than all of them. One may think of R as the new number when at least M smaller possibilities can be ignored. The Rth smallest element is the Kth smallest element when recurring into the right sub-tree (But keep in mind that R != K !).
  • If K is location(median(T)), then that node contains the Kth smallest element in perfect BST.

Below is the implementation of the above approach:


Output
35 

Time complexity: O(Log(N)) 
Auxiliary Space: O(Log(N))

Comment