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