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)) ;
}
---------------------------------------------------------------------------------
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
Post a Comment