The Wayback Machine - https://web.archive.org/web/20240822105506/https://www.geeksforgeeks.org/kth-largest-element-in-bst-when-modification-to-bst-is-not-allowed/
Open In App

K’th Largest Element in BST when modification to BST is not allowed

Last Updated : 29 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a Binary Search Tree (BST) and a positive integer k, find the k’th largest element in the Binary Search Tree. 
For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then output should be 10. 

We have discussed two methods in this post. The method 1 requires O(n) time. The method 2 takes O(h) time where h is height of BST, but requires augmenting the BST (storing count of nodes in left subtree with every node). 
Can we find k’th largest element in better than O(n) time and no augmentation?

Recommended Practice

Approach: 

  1. The idea is to do reverse inorder traversal of BST. Keep a count of nodes visited.
  2. The reverse inorder traversal traverses all nodes in decreasing order, i.e, visit the right node then centre then left and continue traversing the nodes recursively.
  3. While doing the traversal, keep track of the count of nodes visited so far.
  4. When the count becomes equal to k, stop the traversal and print the key.

Implementation:

C++




// C++ program to find k'th largest element in BST
#include<bits/stdc++.h>
using namespace std;
 
struct Node
{
    int key;
    Node *left, *right;
};
 
// A utility function to create a new BST node
Node *newNode(int item)
{
    Node *temp = new Node;
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// A function to find k'th largest element in a given tree.
void kthLargestUtil(Node *root, int k, int &c;)
{
    // Base cases, the second condition is important to
    // avoid unnecessary recursive calls
    if (root == NULL || c >= k)
        return;
 
    // Follow reverse inorder traversal so that the
    // largest element is visited first
    kthLargestUtil(root->right, k, c);
 
    // Increment count of visited nodes
    c++;
 
    // If c becomes k now, then this is the k'th largest
    if (c == k)
    {
        cout << "K'th largest element is "
             << root->key << endl;
        return;
    }
 
    // Recur for left subtree
    kthLargestUtil(root->left, k, c);
}
 
// Function to find k'th largest element
void kthLargest(Node *root, int k)
{
    // Initialize count of nodes visited as 0
    int c = 0;
 
    // Note that c is passed by reference
    kthLargestUtil(root, k, c);
}
 
/* A utility function to insert a new node with given key in BST */
Node* insert(Node* node, int key)
{
    /* If the tree is empty, return a new node */
    if (node == NULL) return newNode(key);
 
    /* Otherwise, recur down the tree */
    if (key < node->key)
        node->left  = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);
 
    /* return the (unchanged) node pointer */
    return node;
}
 
// Driver Program to test above functions
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
    Node *root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    int c = 0;
    for (int k=1; k<=7; k++)
        kthLargest(root, k);
 
    return 0;
}


Java




// Java code to find k'th largest element in BST
 
// A binary tree node
class Node {
 
    int data;
    Node left, right;
 
    Node(int d)
    {
        data = d;
        left = right = null;
    }
}
 
class BinarySearchTree {
 
    // Root of BST
    Node root;
 
    // Constructor
    BinarySearchTree()
    {
        root = null;
    }
     
    // function to insert nodes
    public void insert(int data)
    {
        this.root = this.insertRec(this.root, data);
    }
     
    /* A utility function to insert a new node
    with given key in BST */
    Node insertRec(Node node, int data)
    {  
        /* If the tree is empty, return a new node */
        if (node == null) {
            this.root = new Node(data);
            return this.root;
        }
 
        if (data == node.data) {
            return node;
        }
         
        /* Otherwise, recur down the tree */
        if (data < node.data) {
            node.left = this.insertRec(node.left, data);
        } else {
            node.right = this.insertRec(node.right, data);
        }
        return node;
    }
 
    // class that stores the value of count
    public class count {
        int c = 0;
    }
 
    // utility function to find kth largest no in
    // a given tree
    void kthLargestUtil(Node node, int k, count C)
    {
        // Base cases, the second condition is important to
        // avoid unnecessary recursive calls
        if (node == null || C.c >= k)
            return;
         
        // Follow reverse inorder traversal so that the
        // largest element is visited first
        this.kthLargestUtil(node.right, k, C);
         
        // Increment count of visited nodes
        C.c++;
         
        // If c becomes k now, then this is the k'th largest
        if (C.c == k) {
            System.out.println(k + "th largest element is " +
                                                 node.data);
            return;
        }
         
        // Recur for left subtree
        this.kthLargestUtil(node.left, k, C);
    }
 
    // Method to find the kth largest no in given BST
    void kthLargest(int k)
    {
        count c = new count(); // object of class count
        this.kthLargestUtil(this.root, k, c);
    }
 
    // Driver function
    public static void main(String[] args)
    {
        BinarySearchTree tree = new BinarySearchTree();
         
        /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
        tree.insert(50);
        tree.insert(30);
        tree.insert(20);
        tree.insert(40);
        tree.insert(70);
        tree.insert(60);
        tree.insert(80);
 
        for (int i = 1; i <= 7; i++) {
            tree.kthLargest(i);
        }
    }
}
 
// This code is contributed by Kamal Rawal


Python3




# Python3 program to find k'th largest
# element in BST
 
class Node:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.key = data
        self.left = None
        self.right = None
         
# A function to find k'th largest
# element in a given tree.
def kthLargestUtil(root, k, c):
     
    # Base cases, the second condition
    # is important to avoid unnecessary
    # recursive calls
    if root == None or c[0] >= k:
        return
 
    # Follow reverse inorder traversal
    # so that the largest element is
    # visited first
    kthLargestUtil(root.right, k, c)
 
    # Increment count of visited nodes
    c[0] += 1
 
    # If c becomes k now, then this is
    # the k'th largest
    if c[0] == k:
        print("K'th largest element is",
                               root.key)
        return
 
    # Recur for left subtree
    kthLargestUtil(root.left, k, c)
 
# Function to find k'th largest element
def kthLargest(root, k):
     
    # Initialize count of nodes
    # visited as 0
    c = [0]
 
    # Note that c is passed by reference
    kthLargestUtil(root, k, c)
 
# A utility function to insert a new
# node with given key in BST */
def insert(node, key):
     
    # If the tree is empty,
    # return a new node
    if node == None:
        return Node(key)
 
    # Otherwise, recur down the tree
    if key < node.key:
        node.left = insert(node.left, key)
    elif key > node.key:
        node.right = insert(node.right, key)
 
    # return the (unchanged) node pointer
    return node
 
# Driver Code
if __name__ == '__main__':
     
    # Let us create following BST
    #         50
    #     /     \
    #     30     70
    # / \ / \
    # 20 40 60 80 */
    root = None
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    for k in range(1,8):
        kthLargest(root, k)
         
# This code is contributed by PranchalK


C#




using System;
 
// C# code to find k'th largest element in BST
 
// A binary tree node
public class Node
{
 
    public int data;
    public Node left, right;
 
    public Node(int d)
    {
        data = d;
        left = right = null;
    }
}
 
public class BinarySearchTree
{
 
    // Root of BST
    public Node root;
 
    // Constructor
    public BinarySearchTree()
    {
        root = null;
    }
 
    // function to insert nodes
    public virtual void insert(int data)
    {
        this.root = this.insertRec(this.root, data);
    }
 
    /* A utility function to insert a new node 
    with given key in BST */
    public virtual Node insertRec(Node node, int data)
    {
        /* If the tree is empty, return a new node */
        if (node == null)
        {
            this.root = new Node(data);
            return this.root;
        }
 
        if (data == node.data)
        {
            return node;
        }
 
        /* Otherwise, recur down the tree */
        if (data < node.data)
        {
            node.left = this.insertRec(node.left, data);
        }
        else
        {
            node.right = this.insertRec(node.right, data);
        }
        return node;
    }
 
    // class that stores the value of count
    public class count
    {
        private readonly BinarySearchTree outerInstance;
 
        public count(BinarySearchTree outerInstance)
        {
            this.outerInstance = outerInstance;
        }
 
        internal int c = 0;
    }
 
    // utility function to find kth largest no in 
    // a given tree
    public virtual void kthLargestUtil(Node node, int k, count C)
    {
        // Base cases, the second condition is important to
        // avoid unnecessary recursive calls
        if (node == null || C.c >= k)
        {
            return;
        }
 
        // Follow reverse inorder traversal so that the
        // largest element is visited first
        this.kthLargestUtil(node.right, k, C);
 
        // Increment count of visited nodes
        C.c++;
 
        // If c becomes k now, then this is the k'th largest 
        if (C.c == k)
        {
            Console.WriteLine(k + "th largest element is " + node.data);
            return;
        }
 
        // Recur for left subtree
        this.kthLargestUtil(node.left, k, C);
    }
 
    // Method to find the kth largest no in given BST
    public virtual void kthLargest(int k)
    {
        count c = new count(this); // object of class count
        this.kthLargestUtil(this.root, k, c);
    }
 
    // Driver function
    public static void Main(string[] args)
    {
        BinarySearchTree tree = new BinarySearchTree();
 
        /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
        tree.insert(50);
        tree.insert(30);
        tree.insert(20);
        tree.insert(40);
        tree.insert(70);
        tree.insert(60);
        tree.insert(80);
 
        for (int i = 1; i <= 7; i++)
        {
            tree.kthLargest(i);
        }
    }
}
 
  // This code is contributed by Shrikant13


Javascript




<script>
// javascript code to find k'th largest element in BST
 
// A binary tree node
class Node {
 
   constructor(d)
    {
        this.data = d;
        this.left = this.right = null;
    }
}
 
 
 
    // Root of BST
    var root = null;
 
    // Constructor
    
     
    // function to insert nodes
    function insert(data)
    {
        this.root = this.insertRec(this.root, data);
    }
     
    /* A utility function to insert a new node
    with given key in BST */
    function insertRec( node , data)
    {  
        /* If the tree is empty, return a new node */
        if (node == null) {
            this.root = new Node(data);
            return this.root;
        }
 
        if (data == node.data) {
            return node;
        }
         
        /* Otherwise, recur down the tree */
        if (data < node.data) {
            node.left = this.insertRec(node.left, data);
        } else {
            node.right = this.insertRec(node.right, data);
        }
        return node;
    }
 
    // class that stores the value of count
     class count {
        constructor(){this.c = 0;}
   
    }
 
    // utility function to find kth largest no in
    // a given tree
    function kthLargestUtil( node , k,  C)
    {
        // Base cases, the second condition is important to
        // avoid unnecessary recursive calls
        if (node == null || C.c >= k)
            return;
         
        // Follow reverse inorder traversal so that the
        // largest element is visited first
        this.kthLargestUtil(node.right, k, C);
         
        // Increment count of visited nodes
        C.c++;
         
        // If c becomes k now, then this is the k'th largest
        if (C.c == k) {
            document.write(k + "th largest element is " +
                                                 node.data+"<br/>");
            return;
        }
         
        // Recur for left subtree
        this.kthLargestUtil(node.left, k, C);
    }
 
    // Method to find the kth largest no in given BST
    function kthLargest(k)
    {
         c = new count(); // object of class count
        this.kthLargestUtil(this.root, k, c);
    }
 
    // Driver function
     
  
         
        /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
        insert(50);
        insert(30);
        insert(20);
        insert(40);
        insert(70);
        insert(60);
        insert(80);
 
        for (i = 1; i <= 7; i++) {
            kthLargest(i);
        }
 
// This code contributed by gauravrajput1
</script>


Output

K'th largest element is 80
K'th largest element is 70
K'th largest element is 60
K'th largest element is 50
K'th largest element is 40
K'th largest element is 30
K'th largest element is 20







Complexity Analysis:  

  1. Time Complexity: O(n). 
    In worst case the code can traverse each and every node of the tree if the k given is equal to n (total number of nodes in the tree). Therefore overall time complexity is O(n).
  2. Auxiliary Space: O(h). 
    Max recursion stack of height h at a given time.

This article is contributed by Chirag Sharma.

Approach 2:-  Iterative approach

The idea is to do reverse inorder traversal of BST. Keep a count of nodes visited.
The reverse inorder traversal traverses all nodes in decreasing order, i.e, visit the right node then centre then left and continue traversing the nodes recursively.
While doing the traversal, keep track of the count of nodes visited so far.
When the count becomes equal to k, stop the traversal and print the key. 

Time Complexity : – O(N)

C++




#include <iostream>
#include <stack>
 
using namespace std;
 
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
 
int kthLargest(TreeNode* root, int k) {
    stack<TreeNode*> st;
    TreeNode* curr = root;
    int count = 0;
    while (curr != NULL || !st.empty()) {
        while (curr != NULL) {
            st.push(curr);
            curr = curr->right;
        }
        curr = st.top();
        st.pop();
        count++;
        if (count == k) {
            return curr->val;
        }
        curr = curr->left;
    }
    return -1; // kth largest element does not exist
}
 
int main() {
    // create a BST
    TreeNode* root = new TreeNode(5);
    root->left = new TreeNode(3);
    root->right = new TreeNode(7);
    root->left->left = new TreeNode(2);
    root->left->right = new TreeNode(4);
    root->right->left = new TreeNode(6);
    root->right->right = new TreeNode(8);
 
    // find the kth largest element
    int k = 3;
    int kth_largest = kthLargest(root, k);
    if (kth_largest != -1) {
        cout << "The " << k << "th largest element is: " << kth_largest << endl;
    } else {
        cout << "The " << k << "th largest element does not exist" << endl;
    }
 
    return 0;
}


Java




import java.util.Stack;
 
// Creating Tree
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
 
    public TreeNode(int x) {
        val = x;
        left = null;
        right = null;
    }
}
 
// Function to find kth largest element
class KthLargestElementBST {
    public static int kthLargest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curr = root;
        int count = 0;
        while (curr != null || !stack.empty()) {
            while (curr != null) {
                stack.push(curr);
                curr = curr.right;
            }
            curr = stack.pop();
            count++;
            if (count == k) {
                return curr.val;
            }
            curr = curr.left;
        }
        return -1; // kth largest element does not exist
    }
 
  // Driver code
    public static void main(String[] args) {
        // create a BST
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(3);
        root.right = new TreeNode(7);
        root.left.left = new TreeNode(2);
        root.left.right = new TreeNode(4);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(8);
 
        // find the kth largest element
        int k = 3;
        int kth_largest = kthLargest(root, k);
        if (kth_largest != -1) {
            System.out.println("The " + k + "th largest element is: " + kth_largest);
        } else {
            System.out.println("The " + k + "th largest element does not exist");
        }
    }
}


Python3




class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
 
def kthLargest(root: TreeNode, k: int) -> int:
    st = []
    curr = root
    count = 0
    while curr or st:
        while curr:
            st.append(curr)
            curr = curr.right
        curr = st.pop()
        count += 1
        if count == k:
            return curr.val
        curr = curr.left
    return -1
 
# create a BST
root = TreeNode(5)
root.left = TreeNode(3)
root.right = TreeNode(7)
root.left.left = TreeNode(2)
root.left.right = TreeNode(4)
root.right.left = TreeNode(6)
root.right.right = TreeNode(8)
 
# find the kth largest element
k = 3
kth_largest = kthLargest(root, k)
if kth_largest != -1:
    print(f"The {k}th largest element is: {kth_largest}")
else:
    print(f"The {k}th largest element does not exist")


C#




using System;
using System.Collections.Generic;
 
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
 
    public TreeNode(int x)
    {
        val = x;
        left = null;
        right = null;
    }
}
 
public class KthLargestElementBST {
    // Function to find kth largest element
    public static int KthLargest(TreeNode root, int k)
    {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode curr = root;
        int count = 0;
        while (curr != null || stack.Count > 0) {
            while (curr != null) {
                stack.Push(curr);
                curr = curr.right;
            }
            curr = stack.Pop();
            count++;
            if (count == k) {
                return curr.val;
            }
            curr = curr.left;
        }
        return -1; // kth largest element does not exist
    }
 
    // Driver code
    public static void Main()
    {
        // create a BST
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(3);
        root.right = new TreeNode(7);
        root.left.left = new TreeNode(2);
        root.left.right = new TreeNode(4);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(8);
 
        // find the kth largest element
        int k = 3;
        int kth_largest = KthLargest(root, k);
        if (kth_largest != -1) {
            Console.WriteLine("The " + k
                              + "th largest element is: "
                              + kth_largest);
        }
        else {
            Console.WriteLine(
                "The " + k
                + "th largest element does not exist");
        }
    }
}


Javascript




class TreeNode {
  constructor(x) {
    this.val = x;
    this.left = null;
    this.right = null;
  }
}
 
function kthLargest(root, k) {
  const st = [];
  let curr = root;
  let count = 0;
  while (curr || st.length) {
    while (curr) {
      st.push(curr);
      curr = curr.right;
    }
    curr = st.pop();
    count++;
    if (count === k) {
      return curr.val;
    }
    curr = curr.left;
  }
  return -1;
}
 
// create a BST
const root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(7);
root.left.left = new TreeNode(2);
root.left.right = new TreeNode(4);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(8);
 
// find the kth largest element
const k = 3;
const kth_largest = kthLargest(root, k);
if (kth_largest !== -1) {
  console.log(`The ${k}th largest element is: ${kth_largest}`);
} else {
  console.log(`The ${k}th largest element does not exist`);
}


Output

The 3th largest element is: 6







 Time complexity  –The time complexity of the kthLargest function is O(h + k), where h is the height of the binary search tree and k is the given value for finding the kth largest element. This is because in the worst case, the function will need to traverse the height of the tree and then traverse k elements to find the kth largest element.

Space complexity –The space complexity of the kthLargest function is O(h), where h is the height of the binary search tree. This is because the function uses a stack to store the nodes in the right subtree, which can have at most h nodes if the tree is skewed.

Using a Max Heap:

Follow the steps to implement the above approach:

  1. Create an empty max heap of integers using the C++ STL priority_queue container.
  2. Traverse the binary search tree in reverse in-order sequence using a stack.
  3. At each node, add the node value to the max heap.
  4. If the size of the max heap becomes greater than K, remove the maximum element from the max heap.
  5. After we finish traversing the binary search tree, the maximum element in the max heap will be the Kth largest element in the binary search tree.

Below is the implementation of the above approach:

C++




// C++ code to implement maxHeap approach
#include <bits/stdc++.h>
using namespace std;
 
// Definition of a binary tree node
struct Node {
    int data;
    Node *left, *right;
    Node(int val)
    {
        data = val;
        left = right = NULL;
    }
};
// Function to implement maxHeap approach
int kthLargest(Node* root, int K)
{
    priority_queue<int> maxHeap;
    // Traverse the binary search tree and add elements to
    // the max heap
    stack<Node*> s;
    Node* curr = root;
    while (curr != NULL || s.empty() == false) {
        while (curr != NULL) {
            s.push(curr);
            curr = curr->right;
        }
        curr = s.top();
        s.pop();
        maxHeap.push(curr->data);
        curr = curr->left;
    }
    // Remove K-1 elements from the max heap
    for (int i = 1; i < K; i++) {
        maxHeap.pop();
    }
    // The top element of the max heap is the Kth largest
    // element
    return maxHeap.top();
}
// Driver Code
int main()
{
    // Example binary search tree
    /*
              4
            /   \
           2     9
                / \
               7  10
    */
    Node* root = new Node(4);
    root->left = new Node(2);
    root->right = new Node(9);
    root->right->left = new Node(7);
    root->right->right = new Node(10);
 
    int K = 2;
    int kthLargestElement = kthLargest(root, K);
 
    cout << "The " << K
         << "th largest element in the binary search tree "
            "is: "
         << kthLargestElement << endl;
    return 0;
}
// This code is contributed by Veerendra_Singh_Rajpoot


Java




import java.util.PriorityQueue;
import java.util.Stack;
 
// Definition of a binary tree node
class Node {
    int data;
    Node left, right;
 
    Node(int val) {
        data = val;
        left = right = null;
    }
}
 
public class KthLargestElement {
 
    // Function to implement maxHeap approach to find the Kth largest element
    public static int kthLargest(Node root, int K) {
        // Create a max heap to store the largest elements
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
 
        // Traverse the binary search tree and add elements to the max heap
        Stack<Node> stack = new Stack<>();
        Node curr = root;
        while (curr != null || !stack.isEmpty()) {
            while (curr != null) {
                stack.push(curr);
                curr = curr.right;
            }
            curr = stack.pop();
            maxHeap.add(curr.data);
            curr = curr.left;
        }
 
        // Remove K-1 elements from the max heap
        for (int i = 1; i < K; i++) {
            maxHeap.poll();
        }
 
        // The top element of the max heap is the Kth largest element
        return maxHeap.peek();
    }
 
    // Driver Code
    public static void main(String[] args) {
        // Example binary search tree
        /*
                  4
                /   \
               2     9
                    / \
                   7  10
        */
        Node root = new Node(4);
        root.left = new Node(2);
        root.right = new Node(9);
        root.right.left = new Node(7);
        root.right.right = new Node(10);
 
        int K = 2;
        int kthLargestElement = kthLargest(root, K);
 
        System.out.println("The " + K + "th largest element in the binary search tree is: " + kthLargestElement);
    }
}


Python3




import heapq
 
# Definition of a binary tree node
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None
 
# Function to implement maxHeap approach
def kthLargest(root, K):
    maxHeap = []
    # Traverse the binary search tree and add elements to
    # the max heap
    stack = []
    curr = root
    while curr or stack:
        while curr:
            stack.append(curr)
            curr = curr.right
        curr = stack.pop()
        heapq.heappush(maxHeap, -curr.data)
        curr = curr.left
    # Remove K-1 elements from the max heap
    for i in range(K - 1):
        heapq.heappop(maxHeap)
    # The top element of the max heap is the Kth largest
    # element
    return -maxHeap[0]
 
# Driver Code
if __name__ == '__main__':
    # Example binary search tree
    '''
              4
            /   \
           2     9
                / \
               7  10
    '''
    root = Node(4)
    root.left = Node(2)
    root.right = Node(9)
    root.right.left = Node(7)
    root.right.right = Node(10)
 
    K = 2
    kthLargestElement = kthLargest(root, K)
 
    print(f"The {K}th largest element in the binary search tree is: {kthLargestElement}")


C#




// C# code to implement maxHeap approach
using System;
using System.Collections.Generic;
 
// Definition of a binary tree node
class Node
{
    public int Data;
    public Node Left, Right;
 
    public Node(int val)
    {
        Data = val;
        Left = Right = null;
    }
}
 
class GFG
{
    // Function to implement maxHeap approach
    static int KthLargest(Node root, int K)
    {
        // Create a max heap
        List<int> maxHeap = new List<int>();
 
        // Traverse the binary search tree and add elements to the max heap
        Stack<Node> stack = new Stack<Node>();
        Node curr = root;
 
        while (curr != null || stack.Count > 0)
        {
            while (curr != null)
            {
                stack.Push(curr);
                curr = curr.Right;
            }
            curr = stack.Pop();
            maxHeap.Add(curr.Data);
            curr = curr.Left;
        }
 
        // Sort the max heap in descending order
        maxHeap.Sort((x, y) => y.CompareTo(x));
 
        // The Kth largest element is at index K-1
        return maxHeap[K - 1];
    }
 
    // Driver Code
    static void Main(string[] args)
    {
        // Example binary search tree
        /*
                  4
                /   \
               2     9
                    / \
                   7  10
        */
        Node root = new Node(4);
        root.Left = new Node(2);
        root.Right = new Node(9);
        root.Right.Left = new Node(7);
        root.Right.Right = new Node(10);
 
        int K = 2;
        int kthLargestElement = KthLargest(root, K);
 
        Console.WriteLine("The " + K + "th largest element in the binary search tree is: " + kthLargestElement);
    }
}
 
// This code is contributed by Susobhan Akhuli


Javascript




// Definition of a binary tree node
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}
 
// Function to implement maxHeap approach
function kthLargest(root, K) {
    const maxHeap = new MaxHeap();
 
    // Traverse the binary search tree and add elements to the max heap
    const stack = [];
    let curr = root;
    while (curr !== null || stack.length > 0) {
        while (curr !== null) {
            stack.push(curr);
            curr = curr.right;
        }
        curr = stack.pop();
        maxHeap.push(curr.data);
        curr = curr.left;
    }
 
    // Remove K-1 elements from the max heap
    for (let i = 1; i < K; i++) {
        maxHeap.pop();
    }
 
    // The top element of the max heap is the Kth largest element
    return maxHeap.top();
}
 
// MaxHeap implementation
class MaxHeap {
    constructor() {
        this.heap = [];
    }
 
    push(val) {
        this.heap.push(val);
        this.heapifyUp(this.heap.length - 1);
    }
 
    pop() {
        if (this.heap.length === 0) {
            return null;
        }
        if (this.heap.length === 1) {
            return this.heap.pop();
        }
 
        const root = this.heap[0];
        this.heap[0] = this.heap.pop();
        this.heapifyDown(0);
        return root;
    }
 
    top() {
        if (this.heap.length === 0) {
            return null;
        }
        return this.heap[0];
    }
 
    heapifyUp(index) {
        while (index > 0) {
            const parentIndex = Math.floor((index - 1) / 2);
            if (this.heap[index] <= this.heap[parentIndex]) {
                break;
            }
            [this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]];
            index = parentIndex;
        }
    }
 
    heapifyDown(index) {
        while (true) {
            const leftChildIndex = 2 * index + 1;
            const rightChildIndex = 2 * index + 2;
            let largestIndex = index;
 
            if (leftChildIndex < this.heap.length && this.heap[leftChildIndex] >
            this.heap[largestIndex]) {
                largestIndex = leftChildIndex;
            }
 
            if (rightChildIndex < this.heap.length && this.heap[rightChildIndex] >
             this.heap[largestIndex]) {
                largestIndex = rightChildIndex;
            }
 
            if (largestIndex === index) {
                break;
            }
 
            [this.heap[index], this.heap[largestIndex]] =
            [this.heap[largestIndex], this.heap[index]];
            index = largestIndex;
        }
    }
}
 
// Driver Code
// Example binary search tree
/*
          4
        /   \
       2     9
            / \
           7  10
*/
const root = new Node(4);
root.left = new Node(2);
root.right = new Node(9);
root.right.left = new Node(7);
root.right.right = new Node(10);
 
const K = 2;
const kthLargestElement = kthLargest(root, K);
 
console.log(`The ${K}th largest element in the binary search tree is: ${kthLargestElement}`);
// This code is contributed by Veerendra_Singh_Rajpoot


Output

The 2th largest element in the binary search tree is: 9







Time Complexity: O(n logk) , The worst-case time complexity of building a max heap of size k is O(klogk).
The worst-case time complexity of traversing a binary search tree in reverse in-order sequence is O(n), where n is the number of nodes in the binary search tree.

Space Complexity: O(k), We use a max heap of size k to keep track of the k largest elements in the binary search tree.
Therefore, the overall space complexity of this approach is O(k).



Previous Article
Next Article

Similar Reads

K'th Largest element in BST using constant extra space
Given a binary search tree, task is to find Kth largest element in the binary search tree. Example: Input : k = 3 Root of following BST 10 / \ 4 20 / / \ 2 15 40 Output : 15 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 informat
10 min read
Second largest element in BST
Given a Binary Search Tree (BST), find the second largest element. Example: Input: Root of below BST 10 /5 Output: 5 Input: Root of below BST 10 / \ 5 20 \ 30 Output: 20 Source: Microsoft Interview The idea is similar to below post. K’th Largest Element in BST when modification to BST is not allowedThe second largest element is second last element
9 min read
Largest number with one swap allowed
Given a positive integer, find the largest number that could be generated by swapping only two digits at most once.Examples: Input: 2736 Output : 7236 Explanation: If we swap the number 2 and the number 7 then the generated number would be the largest number. Input : 432 Output : 432 Explanation: Here, no swap is required. The given number is alrea
9 min read
Find the largest rectangle of 1's with swapping of columns allowed
Given a matrix with 0 and 1's, find the largest rectangle of all 1's in the matrix. The rectangle can be formed by swapping any pair of columns of given matrix.Example: Input: bool mat[][] = { {0, 1, 0, 1, 0}, {0, 1, 0, 1, 1}, {1, 1, 0, 1, 0} }; Output: 6 The largest rectangle's area is 6. The rectangle can be formed by swapping column 2 with 3 The
12 min read
Final state of the string after modification
Given a string S of length n representing n boxes adjacent to each other. A character R at index i represents that i-th box is being pushed towards the right.On the other hand, L at index i represents that i-th box is being pushed towards the left.And a . represents an empty space. We start with initial configuration, at every time unit, a box bein
7 min read
Substring segment query &amp; modification
Given a string S containing only uppercase English letters. You have to process Q queries of the given form: 1 x: Print the maximum size of the segment [i, j] where [Tex]0 â‰Ī i â‰Ī x â‰Ī j &lt; |S| [/Tex]and substring S[i...j] contains only the letter S[x].2 x: change S[x] = '#' .Note: For both types of queries, S[x] will not contain the character ‘#’.
9 min read
Largest element smaller than current element on left for every element in Array
Given an array arr[] of the positive integers of size N, the task is to find the largest element on the left side of each index which is smaller than the element present at that index. Note: If no such element is found then print -1. Examples: Input: arr[] = {2, 5, 10} Output: -1 2 5 Explanation : Index 0: There are no elements before it So Print -
11 min read
Maximum sum from three arrays such that picking elements consecutively from same is not allowed
Given three arrays A[], B[], and C[] of N integers. We can choose N elements from this array such that for every index i only one element can be chosen from this array i.e. either A[i], B[i], or C[i], and no two consecutive elements can be chosen from the same array. The task is to print the maximum sum of numbers that we can make by choosing eleme
15+ min read
Maximum sum from a tree with adjacent levels not allowed
Given a binary tree with positive integer values. Find the maximum sum of nodes such that we cannot pick two levels for computing sum Examples: Input : Tree 1 / \ 2 3 / 4 \ 5 / 6 Output :11 Explanation: Total items we can take: {1, 4, 6} or {2, 3, 5}. Max sum = 11. Input : Tree 1 / \ 2 3 / / \ 4 5 6 / \ / / 17 18 19 30 / / \ 11 12 13 Output :89 Exp
7 min read
POTD Solutions | 15 Oct' 23 | Normal BST to Balanced BST
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Search Trees but will also help you build up problem-solving skills. POTD 15 October: Normal BST t
5 min read
Two nodes of a BST are swapped, correct the BST
Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST. Input: 10 / \ 5 8 / \ 2 20Output: 10 / \ 5 20 / \ 2 8Explanation: The nodes 20 and 8 were swapped Input: 10 / \ 5 8 / \ 2 20Output: 5 / \ 10 20 / \ 2 8Explanation: The nodes 10 and 5 were swapped Approach: The in-order traversal of a BST produces a sorted array. S
15+ min read
k-th Smallest in BST (Order Statistics in BST)
Given the root of a binary search tree and K as input, find Kth smallest element in BST.  For example, in the following BST, if k = 3, then the output should be 10, and if k = 5, then the output should be 14. Using Inorder (O(n) time and O(h) space) The Inorder Traversal of a BST traverses the nodes in increasing order. So the idea is to traverse t
15+ min read
Count of subarrays with largest element at least twice the largest of remaining elements
Given an array arr[] consisting of N positive integers, the task is to find the count of subarrays such that the maximum element of the subarray is greater than twice the maximum of all other elements of the array. Examples: Input: arr[] = {1, 6, 10, 9, 7, 3}Output: 4Explanation:Below are the subarrays satisfying the given condition: Consider the s
14 min read
Largest number not exceeding N that does not contain any of the digits of S
Given a numberic string N (1 â‰Ī |N| â‰Ī 105) and another numeric string S (1 â‰Ī |S| â‰Ī 105), the task is to find the maximum number â‰Ī N such that it doesn't contain digits of string S. Remove leading zeros, if required. Note: The string S doesn't contain '0'. Examples: Input: N = "2004", S = "2" Output: 1999 Explanation: 2004 has digit 2 which is in the
14 min read
Sort an array with swapping only with a special element is allowed
Given an array of length n + 1, containing elements 1 through n and a space, Requires the use of a given swap (index i, index j) function to sort the array, You can only swap the gap and a number, in the end, put the gap at the end. There will be a number 999 in the array as a gap or space. Examples: Input : arr = {1, 5, 4, 999, 3, 2} Output : arr
10 min read
Queries to replace subarrays by equal length arrays with at most P replacements allowed for any array element
Given an array, arr[] of size N, an integer P and a 2D array Q[][] consisting of queries of the following type: 1 L R B[R - L + 1]: The task for this query is to replace the subarray {arr[L], ... arr[R] with the array B[] b given that any array element can be replaced at most P times.2 X: The task for this query is to print arr[X]. Examples: Input:
15+ min read
Maximize score by matching element with prediction and K switch are allowed
Given an array arr[] of size N, with values either 1, 2, or 3. Traverse the array from left to right and before traversal predict one number from 1, 2, or 3, if arr[i] is matched with the prediction score will be increased by 1. The prediction can be switched at most K times. Find the maximum score possible. Examples: Input: A[] = {1, 1, 2, 1, 3},
12 min read
Find n-th element in a series with only 2 digits (4 and 7) allowed
Consider a series of numbers composed of only digits 4 and 7. First few numbers in the series are 4, 7, 44, 47, 74, 44744,.. etc. Given a number n, we need to find n-th number in the series.Examples: Input : n = 2Output : 7 Input : n = 3Output : 44 Input : n = 5Output : 74 Input : n = 6Output : 77 Recommended PracticeElement in a SeriesTry It! The
5 min read
Find n-th element in a series with only 2 digits (4 and 7) allowed | Set 2 (log(n) method)
Consider a series of numbers composed of only digits 4 and 7. First few numbers in the series are 4, 7, 44, 47, 74, 77, 444, .. etc. Given a number n, we need to find n-th number in the series.Examples: Input : n = 2 Output : 7 Input : n = 3 Output : 44 Input : n = 5 Output : 74 Input : n = 6 Output : 77 Recommended: Please solve it on “PRACTICE ”
5 min read
Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.Operation
8 min read
Maximize number of groups formed with size not smaller than its largest element
Given an array arr[] of N positive integers(1 ? arr[i] ? N ), divide the elements of the array into groups such that the size of each group is greater than or equal to the largest element of that group. It may be also possible that an element cannot join any group. The task is to maximize the number of groups. Examples: Input: arr = {2, 3, 1, 2, 2}
7 min read
Find the array element from indices not divisible by K having largest composite product of digits
Given an array arr[] and an integer K, the task is to find the array element from indices not divisible by K whose product of digits is a composite number. Examples: Input: arr[] = {233, 144, 89, 71, 13, 21, 11, 34, 55, 23}, K = 3 Output: 89 Explanation: Following elements have product of digits as a composite number: arr[0] = 233 : Product of digi
12 min read
Find the largest BST subtree in a given Binary Tree | Set 3
Largest BST in a Binary Tree | Set 3Method 3 (Shorter, Smarter and More Efficient) In this section, a different O(n) solution is discussed. This solution is simpler than the solutions discussed in Set-1 and Set-2 and works in O(n) time. In this method, we do not need to check explicitly if the binary tree is BST. A Tree is BST if the following is t
8 min read
Largest number less than or equal to N in BST (Iterative Approach)
We have a binary search tree and a number N. Our task is to find the greatest number in the binary search tree that is less than or equal to N. Print the value of the element if it exists otherwise print -1. Examples: For the above given binary search tree- Input : N = 24 Output :result = 21 (searching for 24 will be like-5-&gt;12-&gt;21) Input : N
7 min read
Sum of k largest elements in BST
Given a BST, the task is to find the sum of all elements greater than and equal to kth largest element. Examples: Input : K = 3 8 / \ 7 10 / / \ 2 9 13 Output : 32 Explanation: 3rd largest element is 9 so sum of all elements greater than or equal to 9 are 9 + 10 + 13 = 32. Input : K = 2 8 / \ 5 11 / \ 2 7 \ 3 Output : 19 Explanation: 2nd largest el
9 min read
Sum of K largest elements in BST using O(1) Extra space
Given a BST, the task is to find the sum of all elements greater than or equal to K-th largest element in O(1) space.Examples: Input : K = 3 8 / \ 7 10 / / \ 2 9 13 Output : 32 Explanation: 3rd largest element is 9 so sum of all elements greater than or equal to 9 are 9 + 10 + 13 = 32. Input : K = 2 8 / \ 5 11 / \ 2 7 \ 3 Output : 19 Explanation: 2
9 min read
Largest number in BST which is less than or equal to N
We have a binary search tree and a number N. Our task is to find the greatest number in the binary search tree that is less than or equal to N. Print the value of the element if it exists otherwise print -1. Examples: For the above given binary search tree- Input : N = 24 Output :result = 21 (searching for 24 will be like-5-&gt;12-&gt;21) Input : N
15 min read
Largest BST in a Binary Tree | Set 2
Given a Binary Tree, write a function that returns the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of the whole tree. Examples:Input: 5 / \ 2 4 / \ 1 3 Output: 3 The following subtree is the maximum size BST subtree 2 / \ 1 3 Input: 50 / \ 30 60 / \ / \ 5 20 45 70 /
11 min read
Replace elements with absolute difference of smallest element on left and largest element on right
Given an array arr[] of N integers. The task is to replace all the elements of the array by the absolute difference of the smallest element on its left and the largest element on its right.Examples: Input: arr[] = {1, 5, 2, 4, 3} Output: 5 3 3 2 1 ElementSmallest on its leftLargest on its rightAbsolute difference1NULL5551432143413231NULL1 Input: ar
15+ min read
Array formed from difference of each element from the largest element in the given array
Given an array arr[], the task is to find the array formed from the difference of each element from the largest element in the given array. Example: Input: arr[] = {3, 6, 9, 2,6} Output: {6, 3, 0, 7, 3} Explanation: Largest element of the array = 9 Therefore difference of arr[i] from 9: Element 1: 9 - 3 = 6 Element 2: 9 - 6 = 3 Element 3: 9 - 9 = 0
5 min read
three90RightbarBannerImg