K’th Largest Element in BST

PROBLEM :

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.



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


/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;                                 */

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

kth_largest_element(root->right,&(*k),&(*no)) ;
if((*k)==1)
(*no)=root->info ;
(*k)-- ;
kth_largest_element(root->left,&(*k),&(*no)) ;
}


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

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 )