Remove BST keys outside the given range

PROBLEM :

Remove BST keys outside the given range

Given a Binary Search Tree (BST) and a range [min, max], remove all keys which are outside the given range. The modified tree should also be BST. For example, consider the following BST and range [-10, 13].



The given tree should be changed to following. Note that all keys outside the range [-10, 13] are removed and modified tree is BST.




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

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

tree* delete_element_tree(tree *,int ) ;

// L is the lower limit and H is the upper limit

tree* remove_range(tree* root,int L,int H)
{
if(root==NULL)
return NULL ;

if(root->info>=L&&root->info<=H)
{
root->left=remove_range(root->left,L,H) ;
root->right=remove_range(root->right,L,H) ;
}
else
{
root=delete_element_tree(root,root->info) ;
root=remove_range(root,L,H) ;
}
return root ;
}

tree* delete_element_tree(tree *root,int ele)
{
if(root==NULL)
return root ;

if(root->info>ele)
root->left=delete_element_tree(root->left,ele) ;

else if(root->info<ele)
root->right=delete_element_tree(root->right,ele) ;

else
{
if(root->right==NULL)
{
tree *temp=root->left ;
free(root) ;
return temp ;
}
if(root->left==NULL)
{
tree *temp=root->right ;
free(root) ;
return temp ;
}

tree *temp=getMin_tree(root->right) ;
root->info=temp->info ;
root->right=delete_element_tree(root->right,root->info) ;
}
}

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

Comments

Post a Comment

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 )