The question is to find the "Kth" smallest element in an array. https://practice.geeksforgeeks.org/problems/kth-smallest-element/0
Now I did see the given techniques but cannot understand them properly. My first intuition after seeing the question was to create a BST from the given array and use the InOrder Traversal of the BST to find the "Kth" smallest element of the array. Here is the code of my approach.
/*
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node* left;
node* right;
};
vector<int> v;//sorted vector
node* insert(node* root,int data){
if(!root){
root = new node();
root->data = data;
root->left = NULL;
root->right = NULL;
return root;
}
if(root->data > data)
root->left = insert(root->left , data);
else
root->right = insert(root->right , data);
return root;
}
void inOrder(node* root){
if(!root)
return;
inOrder(root->left);
v.push_back(root->data);
//cout<<root->data<<" ";
inOrder(root->right);
}
int main() {
int t;
cin>>t;
while(t--){
node* root = NULL;
int n,el;
cin>>n;
for(int i=0;i<n;i++){
cin>>el;
root = insert(root,el);
}
int k;
cin>>k;
inOrder(root);
cout<<v[k-1]<<endl;
v.clear();
}
return 0;
}
*/ Now this according to me should be O(n) in the worst case, but I am not sure. This code gives me a "TLE". Help me fix this code. This is probably the first time I got an intuition to solve a question via a BST so I would like to complete this question via this approach only.
nth_elementis O(n), you could just use that. - cigien