Transform a BST to greater sum tree
PROBLEM :
Transform a BST to greater sum tree
Given a BST, transform it into greater sum tree where each node contains sum of all nodes greater than that node.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ; */
void trasform_greatest_sum_tree(tree **,int *) ;
tree* greater_sum_tree(tree *root)
{
if(root==NULL)
return root;
int sum=0 ;
trasform_greatest_sum_tree(&root,&sum) ;
return root ;
}
void trasform_greatest_sum_tree(tree **root,int *sum)
{
if((*root)==NULL)
return ;
int temp ;
trasform_greatest_sum_tree(&(*root)->right,&(*sum)) ;
temp=(*root)->info ;
(*root)->info=(*sum) ;
(*sum)=(*sum)+temp ;
trasform_greatest_sum_tree(&(*root)->left,&(*sum)) ;
}
---------------------------------------------------------------------------------
Transform a BST to greater sum tree
Given a BST, transform it into greater sum tree where each node contains sum of all nodes greater than that node.
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ; */
void trasform_greatest_sum_tree(tree **,int *) ;
tree* greater_sum_tree(tree *root)
{
if(root==NULL)
return root;
int sum=0 ;
trasform_greatest_sum_tree(&root,&sum) ;
return root ;
}
void trasform_greatest_sum_tree(tree **root,int *sum)
{
if((*root)==NULL)
return ;
int temp ;
trasform_greatest_sum_tree(&(*root)->right,&(*sum)) ;
temp=(*root)->info ;
(*root)->info=(*sum) ;
(*sum)=(*sum)+temp ;
trasform_greatest_sum_tree(&(*root)->left,&(*sum)) ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment