Convert a given tree to its Sum Tree

PROBLEM :

Given a Binary Tree where each node has positive and negative values. Convert this to a tree where each node contains the sum of the left and right sub trees in the original tree. The values of leaf nodes are changed to 0.

For example, the following tree

             10
          /      \
        -2        6
       /   \     /  \
     8     -4   7    5

should be changed to

       20(4-2+12+6)
          /              \
     4(8-4)      12(7+5)
       /   \           /  \
     0      0       0    0



Input:

The task is to complete the method which takes one argument, root of Binary Tree. There are multiple test cases. For each test case, this method will be called individually.

Output:
The function convert the passed tree to its sum tree.

Constraints:
1 <=T<= 30
1 <=Number of nodes<= 100
1 <=Data of a node<= 1000

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

/* A binary tree node
struct Node
{
    int data;
    struct Node* left, * right;
}; */


// Convert a given tree to a tree where every node contains sum of values of
// nodes in left and right subtrees in the original tree

int sum(Node *) ;

void toSumTree(struct Node *root)
{
    if(root==NULL)
    return ;
   
    if(root->left==NULL&&root->right==NULL)
    {
        root->data=0 ;
        return ;
    }
   
    int Lsum ,Rsum ;

    Lsum=sum(root->left) ;
    Rsum=sum(root->right) ;
       
    root->data=Lsum+Rsum ;
   
    toSumTree(root->left) ;
    toSumTree(root->right) ;
}

int sum(Node *root)
{
    if(root==NULL)
        return 0 ;
    return(root->data+sum(root->left)+sum(root->right)) ;
}



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

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 )