VOOZH about

URL: https://www.geeksforgeeks.org/dsa/kth-largest-element-bst-using-constant-extra-space/

⇱ K'th Largest element in BST using constant extra space - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

K'th Largest element in BST using constant extra space

Last Updated : 11 Jul, 2025

Given a Binary Search Tree (BST) and a positive integer k, the task is to find the kth largest element in the Binary Search Tree.

Example:

Input: k = 3

👁 th-Largest-element-in-BST

Output: 14
Explanation: If we sort the BST in decreasing order, then it will become 22, 20, 14, 12, 10, 8, 4. 14 is the 3rd largest element.

Approach:

The idea is to use Reverse Morris Traversal which is based on Threaded Binary Trees. Threaded binary trees use the NULL pointers to store the successor and predecessor information which helps us to utilize the wasted memory by those NULL pointers.

The special thing about Morris traversal is that we can do Inorder traversal without using stack or recursion which saves us memory consumed by stack or recursion call stack. Reverse Morris traversal is just the reverse of Morris traversal which is majorly used to do Reverse Inorder traversal with constant O(1) extra memory consumed as it does not uses any Stack or Recursion.

To find Kth largest element in a Binary search tree, the simplest logic is to do reverse inorder traversal and while doing reverse inorder traversal simply keep a count of number of Nodes visited. When the count becomes equal to k, we stop the traversal and print the data. It uses the fact that reverse inorder traversal will give us a list sorted in descending order. 

Below is the implementation of the above approach:


Output
14

Time Complexity: O(n), where n is the number of nodes in Binary tree.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: