k-th smallest element in BST | Practice | GeeksforGeeks

Given a BST and an integer K. Find the Kth Smallest element in the BST. 
Example 1:
Input:
      2
    /   \
   1     3
K = 2
Output: 2

Example 2:
Input:
        2
      /  \
     1    3
K = 5
Output: -1
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function KthSmallestElement() which takes the root of the BST and integer K as inputs and return the Kth smallest element in the BST, if no such element exists return -1.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).

Constraints:
1<=Number of nodes<=100000
 
-1
amarrajsmart1971 week ago
 void inorder(Node*root,vector<int> &v)   {       if(!root)       {           return ;       }       inorder(root->left,v);       v.push_back(root->data);       inorder(root->right,v);   }      int KthSmallestElement(Node *root, int K) {       // add code here.       vector<int> v;       inorder(root,v);       if(K>v.size())       return -1;       else       return v[K-1];   }
0
joyrockok2 weeks ago
class Solution {int orderCnt=0;int resultValue=-1;public int KthSmallestElement(Node root, int K) {  if(root == null) return -1;
 getElement(root.left, K);  if(root != null) orderCnt++;  if(orderCnt == K) return root.data;  getElement(root.right, K);
 if(resultValue == -1)   return -1; else   return resultValue;}public void getElement(Node node, int K) {  if(node == null)   return;
 getElement(node.left, K); if(node != null) orderCnt++;  if(orderCnt == K) {  resultValue = node.data;  return; } getElement(node.right, K);}
 
} 
0
adarshgupta4012 weeks ago
OPtimal, Easy Java Soln using itertaive inOrder Traversal
class Solution {
    public int KthSmallestElement(Node root, int k) {
        Stack<Node> st = new Stack<>();
        Node node = root;
        int count = 0;
        while( true ){
            if(node != null){
                st.push(node);
                node = node.left;
            }else{
                if(st.isEmpty()) break;
                node = st.peek();
                st.pop();
                count++;
                if(count == k) return node.data;
                
                node = node.right;
            }
        }
        return -1;
    }
}
0
amishasahu3282 weeks ago
void inorder(Node* root, int &k, int &ans)
    {
        if(root == NULL)
        return;
    
        inorder(root -> left, k, ans);
        
        k--;
        
        if(k == 0)
        {
            ans = root -> data;
            return ;
        }
        
        inorder(root -> right, k, ans);
    }
    int KthSmallestElement(Node *root, int K) {
        // add code here.
        int ans = -1;
        inorder(root, K, ans);
        return ans;
    }
0
inspiringseeds3 weeks ago
void solve(Node *root, int &k,int &ans) {     if(root == NULL)       {           return ;       }              solve(root->left,k,ans);       k--;       if(k == 0)       {           ans = root->data;           return ;       }       solve(root->right,k,ans);        }   // Return the Kth smallest element in the given BST   int KthSmallestElement(Node *root, int K) {       // add code here.       int ans = -1;       solve(root,K,ans);       return ans;   }
0
abhibarkade1113 weeks ago
public int KthSmallestElement(Node root, int K) {       // Write your code here       PriorityQueue<Integer> pq = new PriorityQueue<>();       solve(root,pq);       if(pq.size()<K){           return -1;       }       else{           while(K!=1){               pq.poll();               K--;           }       }       return pq.peek();          }   public void solve(Node root, PriorityQueue<Integer> pq){       if(root==null){           return;       }       pq.add(root.data);       solve(root.left, pq);       solve(root.right, pq);   }
0
chhitizgoyal3 weeks ago
Java Solution.
ArrayList<Integer> list = new ArrayList<>();   public int KthSmallestElement(Node root, int k) {            if(root==null){           return -1;       }       KthSmallestElement(root.left, k);       list.add(root.data);       KthSmallestElement(root.right, k);       if(k>list.size()){           return -1;       }       return list.get(k-1);   }
0
aryankhatana353 weeks ago
C++ sol 
 
int solve(Node *root,int &i ,int K){       if(root==NULL){           return -1;       }       // L       int left=solve(root->left,i,K);       if(left!=-1){           return left;       }              // N       i++;       if(i==K){          return root->data;        }              // R       int right=solve(root->right,i,K);                }      int KthSmallestElement(Node *root, int K) {       // add code here.       int i=0;       int ans=solve(root,i,K);       return ans;   }};
0
sergiojacksonramos3 weeks ago
// Simple Java solution using Inorer traversal ONLY
ArrayList<Integer> arr;
    // Return the Kth smallest element in the given BST
    public int KthSmallestElement(Node root, int K) {
        // Write your code here
        arr = new ArrayList<>();
        inorder(root, arr);
        if (arr.size() < K) return -1;
        return arr.get(K-1);
    }
    
    static void inorder(Node root, ArrayList<Integer> arr) {
        if (root == null) return;
        inorder(root.left, arr);
        arr.add(root.data);
        inorder(root.right, arr);
    }
0
sandeep55214 weeks ago
C++ Morris Traversal Solution using O(1) space
int KthSmallestElement(Node *root, int k) {
       Node *cur=root;
       int i=1;
       while(cur){
           if(!(cur->left)){
               if(i==k) return cur->data;
               i++;
               cur=cur->right;
           }
           else{
               Node *p=cur->left;
               while(p->right and p->right!=cur) p=p->right;
               if(!p->right){
                   p->right=cur;
                   cur=cur->left;
               }
               if(p->right==cur){
                   if(i==k) return cur->data;
                   i++;
                   cur=cur->right;
                   p->right=NULL;
               }
           }
       }
       return -1;
   }
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.