Change a Binary Tree so that every node stores sum of all nodes in left subtree

PROBLEM :

Given a Binary Tree, change the value in each node to sum of all the values in the nodes in the left subtree including its own.

Example

Input :
     1
   /   \
 2      3

Output :
    3
  /   \
 2     3


Input
       1
      / \
     2   3
    / \   \
   4   5   6
Output:
      12
     / \
    6   3
   / \   \
  4   5   6

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

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

int BST_left_subTreeSum(tree *root)
{
if(root==NULL)
return 0 ;

if(root->left==NULL&&root->right==NULL)
return root->info ;

int sumL,sumR ;
sumL=BST_left_subTreeSum(root->left) ;
sumR=BST_left_subTreeSum(root->right) ;

root->info=root->info+sumL ;

return root->info+sumR ;
}

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

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 )