Kth largest element in BST | Practice | GeeksforGeeks

Given a Binary search tree. Your task is to complete the function which will return the Kth largest element without doing any modification in Binary Search Tree.

Example 1:
Input:
      4
    /   \
   2     9
k = 2 
Output: 4


Example 2:
Input:
       9
        \ 
          10
K = 1
Output: 10


Your Task:
You don't need to read input or print anything. Your task is to complete the function kthLargest() which takes the root of the BST and an integer K as inputs and returns the Kth largest element in the given BST.

Expected Time Complexity: O(H + K).
Expected Auxiliary Space: O(H)

Constraints:
1 <= N <= 1000
1 <= K <= N
0
18pa1a04771 day ago
without using extra space
def morri(root,ans,ans2=None,val=None):
    cur=root
    while(cur!=None):
        if cur.left==None:
            ans[0]+=1
            # print(ans[0],val)
            if ans[0]==val:
                ans2.append(cur.data)
                break
            cur=cur.right
        else:
            pre=cur.left
            while(pre.right!=None and pre.right!=cur):
                pre=pre.right
            if pre.right==cur:
                ans[0]+=1
                # print(ans[0],val)
                if ans[0]==val:
                    ans2.append(cur.data)
                    break
                cur=cur.right
                pre.right=None
            else:
                pre.right=cur
                cur=cur.left
class Solution:
    def kthLargest(self,root, k):
        ans=[0]
        ans2=[]
        morri(root,ans)
        val=ans[0]-k+1
        ans=[0]
        morri(root,ans,ans2,val)
        return ans2[0]
0
csedeepak4 days ago
simple cpp solution:
void inorder(Node *curr,vector<int> &ans){        if(curr==NULL)            return;        inorder(curr->left,ans);        ans.push_back(curr->data);        inorder(curr->right,ans);;    }   int kthLargest(Node *root, int K)   {       //Your code here       vector<int> ans;       inorder(root,ans);       return ans[ans.size()-K];   }
0
utkarsh061 week ago
JUST DO REVERSE INORDER TRAVERSAL :) 
 void inorder(Node* root, int &K, int &ans)
             {
                 if(!root) return;
                 
                 inorder(root->right,K,ans);
                 
                 K--;
                 if(K==0)
                 {
                     ans = root->data;
                     return;
                 }
                 
                 inorder(root->left,K,ans);
             }
             
             int kthLargest(Node *root, int K)
             {
                 int ans = -1;
                 inorder(root,K,ans);
                 return ans;
             }
0
vishalsavade1 week ago
//Using property of BST Inorder traversal of BST is sorted list - 0.31/1.37
Solution 1: Using N extra space
void inorder(Node *root, vector<int> &v){
        if(root == NULL) return;
        if(root->left)inorder(root->left, v);
        v.push_back(root->data);
        if(root->right)inorder(root->right, v);
    }
    int kthLargest(Node *root, int k)
    {
        //Your code here
        vector<int> v;
        inorder(root, v);
        return v[v.size() - k];
    }
    
 Solution 2: Using 1 extra space - 0.31/1.37
 void inorder(Node *root, int &k, int &ans){
        if(root == NULL) return;
        if(root->right)inorder(root->right, k, ans);
        k--;
        if(k == 0)
            ans = root->data;
        if(root->left)inorder(root->left, k, ans);
        
    }
    int kthLargest(Node *root, int k)
    {
        //Your code here
        int ans = -1;
        inorder(root, k, ans);
        return ans;
    }
+2
ashishbhattacharyya52 weeks ago
 
Easy solution in java
class Solution{   // return the Kth largest element in the given BST rooted at 'root'   ArrayList<Integer> array =new ArrayList<>();      public int kthLargest(Node root,int k)   {       //Your code here     solve(root);     return array.get(k-1);          }   void solve(Node root){         if(root==null){           return ;       }      solve(root.right);       array.add(root.data);               solve(root.left);          }}
0
himanshu567842 weeks ago
class Solution{   void inorder(Node *root,vector<int>& ans)   {       if(!root)return;       inorder(root->left,ans);       ans.push_back(root->data);       inorder(root->right,ans);   }   public:   int kthLargest(Node *root, int K)   {       vector<int> ans;       inorder(root,ans);       return ans.at(ans.size()-K);    }};
+1
anshulgupta966262 weeks ago
void inordertraversal(Node* root, int &k, int &ans) {
        if(root == NULL){
            return;
        }
        else{
            inordertraversal(root->right, k, ans);
            k--;
            if(k == 0){
                ans = root->data;
            }
            inordertraversal(root->left, k, ans);
        }
    }
    
    int kthLargest(Node *root, int K)
    {
        //Your code here
        int ans = -1;
        inordertraversal(root, K, ans);
        return ans;
    }
    
0
f201900382 weeks ago
class Solution
{
    public:
    
    void inordertraversal(Node* root, int &k, int &ans) {
        if(root) {
            inordertraversal(root->right, k, ans);
            k--;
            if(k==0) {
                ans = root->data;
            }
            inordertraversal(root->left, k, ans);
        }
    }
    
    int kthLargest(Node *root, int K)
    {
        int ans = -1;
        inordertraversal(root, K, ans);
        return ans;
    }
};
+1
nothades3 weeks ago
TC: O(n) SC = O(n)
 
	vector<int> v;
    
    void inorder(Node* root)
    {
        if (root==NULL)
            return;
       	inorder(root->left);
       	v.push_back(root->data);
       	inorder(root->right);
    }
    
    int kthLargest(Node *root, int k)
    {
        inorder(root);
        int n = v.size();
        return v[n-k];
    }



0
arankeparth19123 weeks ago
without using extra array:
class Solution{   public:      void solve(Node*root,int k,int& place,int *ans) {              if(root!=NULL) {                      solve(root->right,k,place,ans);           if(place==k && *ans!=-1)               *ans=root->data;           place++;           solve(root->left,k,place,ans);                      }
   }       int kthLargest(Node *root, int K) {       int ans=0;       int place=1;       solve(root,K,place, &ans);       return ans;   }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.