Find k-th smallest element in BST (Order Statistics in BST)

PROBLEM :

Find k-th smallest element in BST (Order Statistics in BST)
Given root of binary search tree and K as input, find K-th smallest element in BST.



For example, in the following BST, if k = 3, then output should be 10, and if k = 5, then output should be 14.

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*  Structure of a Binary Tree
struct Node
{
    int data;
    struct Node* left, *right;
}; */

// root is the root of tree
// no is no of position reached till now , inicially it will be zero
// ele is to save the element at k'th position
// k is the k'th position


 void Kth_smallest_elemet(tree *root,int *no,int *ele,int k)
{
if(root==NULL)
return ;

Kth_smallest_elemet(root->left,&(*no),&(*ele),pos) ;
(*no)++ ;
if((*no)==(pos))
(*ele)=root->info ;
Kth_smallest_elemet(root->right,&(*no),&(*ele),pos) ;
}      

-------------------------------------------------------------------------------
ALTERNATE SOLUTION :
-------------------------------------------------------------------------------
// function returns the element at k'th position


int Kth_smallest_elemet(tree *root,int k)
{
if(root==NULL)
return -1;

int s,i=0 ;
s=size_tree(root) ;

int array[s] ;
inorder_array_fill(root,array,&i) ;

for(i=0;i<s;i++)
{
if(k==1)
return array[i] ;
k-- ;
}
return -1 ;
}

int size_tree(tree* root)
{
if(root==NULL)
return 0 ;

return ((size_tree(root->left))+(size_tree(root->right))+1) ;
}


void inorder_array_fill(tree* root,int a[],int *s)
{
    if(root==NULL)
        return  ;
     
    inorder_array_fill(root->left,a,&(*s)) ;
    a[(*s)++]=root->info ;
    inorder_array_fill(root->right,a,&(*s)) ;
 
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )