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)) ;
}


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

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 )