Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice on BST
  • MCQs on BST
  • BST Tutorial
  • BST Insertion
  • BST Traversals
  • BST Searching
  • BST Deletion
  • Check BST
  • Balance a BST
  • Self-Balancing BST
  • AVL Tree
  • Red-Black Tree
  • Splay Tree
  • BST Application
  • BST Advantage
Open In App
Next Article:
Largest Number in BST which is Less Than or Equal to k
Next article icon

K’th Largest element in BST using constant extra space

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

C++
// C++ Program to find kth largest element #include <bits/stdc++.h> using namespace std;  class Node { public:     int data;     Node *left;     Node *right;     Node(int x) {         data = x;         left = nullptr;         right = nullptr;     } };  // Function to perform Morris Traversal and  // return kth largest element int kthLargest(Node* root, int k) {      // return -1 if root is null     if (root == nullptr) return -1;          Node* curr = root;     int cnt = 0;          while (curr != nullptr) {                  // if right tree does not exists,         // then increment the count, check          // count==k. Otherwise,          // set curr = curr->left         if (curr->right == nullptr) {             cnt++;                          // return current Node             // if cnt == k.             if (cnt == k)                  return curr->data;                              curr = curr->left;             }         else {             Node* succ = curr->right;                          // find the inorder successor             while (succ->left != nullptr &&                     succ->left != curr) {                 succ = succ->left;             }                          // create a linkage between succ and             // curr              if (succ->left == nullptr) {                 succ->left = curr;                 curr = curr->right;             }                          // if succ->left = curr, it means              // we have processed the right subtree,             // and we can process curr node             else {                 cnt++;                                    // remove the link                  succ->left = nullptr;                                  // return current Node                 // if cnt == k.                 if (cnt == k)                      return curr->data;                                  curr = curr->left;             }         }     }          return -1; }  int main() {      // Create a hard coded tree.     //         20     //       /   \     //      8     22     //    /  \       //   4   12       //      /  \     //     10   14     Node* root = new Node(20);     root->left = new Node(8);     root->right = new Node(22);     root->left->left = new Node(4);     root->left->right = new Node(12);     root->left->right->left = new Node(10);     root->left->right->right = new Node(14);          int k = 3;          cout << kthLargest(root, k) << endl;      return 0; } 
C
// C Program to find kth largest element #include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node* left;     struct Node* right; };  // Function to perform Morris Traversal and  // return kth largest element int kthLargest(struct Node* root, int k) {      // return -1 if root is null     if (root == NULL) return -1;      struct Node* curr = root;     int cnt = 0;      while (curr != NULL) {          // if right tree does not exist,         // then increment the count, check          // count == k. Otherwise,          // set curr = curr->left         if (curr->right == NULL) {             cnt++;              // return current Node             // if cnt == k.             if (cnt == k)                 return curr->data;              curr = curr->left;         } else {             struct Node* succ = curr->right;              // find the inorder successor             while (succ->left != NULL && succ->left != curr) {                 succ = succ->left;             }              // create a linkage between pred and curr             if (succ->left == NULL) {                 succ->left = curr;                 curr = curr->right;             }              // if succ->left = curr, it means              // we have processed the right subtree,             // and we can process curr node             else {                 cnt++;                  // remove the link                 succ->left = NULL;                  // return current Node                 // if cnt == k.                 if (cnt == k)                     return curr->data;                  curr = curr->left;             }         }     }      return -1; }  struct Node* createNode(int x) {     struct Node* node =        (struct Node*)malloc(sizeof(struct Node));     node->data = x;     node->left = NULL;     node->right = NULL;     return node; }  int main() {      // Create a hard-coded tree:     //         20     //       /   \     //      8     22     //    /  \     //   4   12     //      /  \     //     10   14     struct Node* root = createNode(20);     root->left = createNode(8);     root->right = createNode(22);     root->left->left = createNode(4);     root->left->right = createNode(12);     root->left->right->left = createNode(10);     root->left->right->right = createNode(14);      int k = 3;      printf("%d\n", kthLargest(root, k));      return 0; } 
Java
// Java Program to find kth largest element class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = right = null;     } }  class GfG {      // Function to perform Morris Traversal      // and return kth largest element     static int kthLargest(Node root, int k) {          // return -1 if root is null         if (root == null) return -1;          Node curr = root;         int cnt = 0;          while (curr != null) {              // if right tree does not exist,             // then increment the count, check              // count == k. Otherwise,              // set curr = curr.left             if (curr.right == null) {                 cnt++;                  // return current Node                 // if cnt == k.                 if (cnt == k) return curr.data;                  curr = curr.left;             } else {                 Node succ = curr.right;                  // find the inorder successor                 while (succ.left != null &&                         succ.left != curr) {                     succ = succ.left;                 }                  // create a linkage between succ and curr                 if (succ.left == null) {                     succ.left = curr;                     curr = curr.right;                 } else {                     cnt++;                      // remove the link                     succ.left = null;                      // return current Node                     // if cnt == k.                     if (cnt == k) return curr.data;                      curr = curr.left;                 }             }         }          return -1;     }      public static void main(String[] args) {          // Create a hard-coded tree:         //         20         //       /   \         //      8     22         //    /  \         //   4   12         //      /  \         //     10   14         Node root = new Node(20);         root.left = new Node(8);         root.right = new Node(22);         root.left.left = new Node(4);         root.left.right = new Node(12);         root.left.right.left = new Node(10);         root.left.right.right = new Node(14);          int k = 3;          System.out.println(kthLargest(root, k));     } } 
Python
# Python Program to find kth largest element class Node:     def __init__(self, data):         self.data = data         self.left = None         self.right = None  # Function to perform Morris Traversal  # and return kth largest element def kth_largest(root, k):      # return -1 if root is null     if root is None:         return -1      curr = root     cnt = 0      while curr is not None:          # if right tree does not exist,         # then increment the count, check          # count == k. Otherwise,          # set curr = curr.left         if curr.right is None:             cnt += 1              # return current Node if cnt == k.             if cnt == k:                 return curr.data              curr = curr.left         else:             succ = curr.right              # find the inorder successor             while succ.left is not None and succ.left != curr:                 succ = succ.left              # create a linkage between succ and curr             if succ.left is None:                 succ.left = curr                 curr = curr.right             else:                 cnt += 1                  # remove the link                 succ.left = None                  # return current Node if cnt == k.                 if cnt == k:                     return curr.data                  curr = curr.left      return -1  if __name__ == "__main__":      # Create a hard-coded tree:     #         20     #       /   \     #      8     22     #    /  \     #   4   12     #      /  \     #     10   14     root = Node(20)     root.left = Node(8)     root.right = Node(22)     root.left.left = Node(4)     root.left.right = Node(12)     root.left.right.left = Node(10)     root.left.right.right = Node(14)      k = 3      print(kth_largest(root, k)) 
C#
// C# Program to find kth largest element using System;  class Node {     public int data;     public Node left, right;      public Node(int x) {         data = x;         left = right = null;     } }  class GfG {      // Function to perform Morris Traversal and      // return kth largest element     static int KthLargest(Node root, int k) {          // return -1 if root is null         if (root == null) return -1;          Node curr = root;         int cnt = 0;          while (curr != null) {              // if right tree does not exist,             // then increment the count, check              // count == k. Otherwise,              // set curr = curr.left             if (curr.right == null) {                 cnt++;                  // return current Node                 // if cnt == k                 if (cnt == k)                     return curr.data;                  curr = curr.left;             } else {                 Node succ = curr.right;                  // find the inorder successor                 while (succ.left != null && succ.left != curr) {                     succ = succ.left;                 }                  // create a linkage between succ and curr                 if (succ.left == null) {                     succ.left = curr;                     curr = curr.right;                 }                                   // if succ.left == curr, it means                  // we have processed the right subtree,                 // and we can process curr node                 else {                     cnt++;                      // remove the link                      succ.left = null;                      // return current Node                     // if cnt == k                     if (cnt == k)                         return curr.data;                      curr = curr.left;                 }             }         }          return -1;     }      static void Main(string[] args) {          // Create a hard-coded tree:         //         20         //       /   \         //      8     22         //    /  \         //   4   12         //      /  \         //     10   14         Node root = new Node(20);         root.left = new Node(8);         root.right = new Node(22);         root.left.left = new Node(4);         root.left.right = new Node(12);         root.left.right.left = new Node(10);         root.left.right.right = new Node(14);          int k = 3;          Console.WriteLine(KthLargest(root, k));     } } 
JavaScript
// JavaScript Program to find kth largest element class Node {     constructor(data) {         this.data = data;         this.left = null;         this.right = null;     } }  // Function to perform Morris Traversal and  // return kth largest element function kthLargest(root, k) {      // return -1 if root is null     if (root === null) return -1;      let curr = root;     let cnt = 0;      while (curr !== null) {          // if right tree does not exist,         // then increment the count, check          // count == k. Otherwise,          // set curr = curr.left         if (curr.right === null) {             cnt++;              // return current Node             // if cnt == k             if (cnt === k)                 return curr.data;              curr = curr.left;         } else {             let succ = curr.right;              // find the inorder successor             while (succ.left !== null && succ.left !== curr) {                 succ = succ.left;             }              // create a linkage between pred and curr             if (succ.left === null) {                 succ.left = curr;                 curr = curr.right;             }                           // if succ.left == curr, it means              // we have processed the right subtree,             // and we can process curr node             else {                 cnt++;                  // remove the link                  succ.left = null;                  // return current Node                 // if cnt == k                 if (cnt === k)                     return curr.data;                  curr = curr.left;             }         }     }      return -1; }  // Create a hard-coded tree: //         20 //       /   \ //      8     22 //    /  \ //   4   12 //      /  \ //     10   14 let root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(4); root.left.right = new Node(12); root.left.right.left = new Node(10); root.left.right.right = new Node(14);  let k = 3;  console.log(kthLargest(root, k)); 

Output
14 

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



Next Article
Largest Number in BST which is Less Than or Equal to k

A

AnishSinghWalia
Improve
Article Tags :
  • Algorithms
  • Binary Search Tree
  • DSA
Practice Tags :
  • Algorithms
  • Binary Search Tree

Similar Reads

  • Binary Search Tree
    A Binary Search Tree (or BST) is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right chi
    3 min read
  • Introduction to Binary Search Tree
    Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
    3 min read
  • Applications of BST
    Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward. The left subtree of a node contains only nod
    2 min read
  • Applications, Advantages and Disadvantages of Binary Search Tree
    A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
    2 min read
  • Insertion in Binary Search Tree (BST)
    Given a BST, the task is to insert a new node in this BST. Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is f
    15+ min read
  • Searching in Binary Search Tree (BST)
    Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
    7 min read
  • Deletion in Binary Search Tree (BST)
    Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios: Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BST Deleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node
    10 min read
  • Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
    Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree.  Input:  Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input:  Output:
    11 min read
  • Balance a Binary Search Tree
    Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height. Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height. Input: Output: Explanation: The above
    10 min read
  • Self-Balancing Binary Search Trees
    Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences