,  

Generate a sum tree of given binary 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:

Approach: The best approach is to do a traversal of the given tree. In the traversal, store the old value of the current node, recursively call for left and right sub trees and change the value of current node as sum of the values returned by the recursive calls. Finally return the sum of new value and value (which is sum of values in the sub tree rooted with this node).
#include <bits/stdc++.h>
using namespace std;
 
struct node{
    int data;
    node *left, *right;
};
 
node* newNode(int data)
{
    node *temp = new node();
    temp->data = data;
    temp->left=NULL;
    temp->right=NULL;
}
 
int sumTree(node *root)
{
    /* If the node is leaf node */
    if(root==NULL)
        return 0;
    /* old_val store the original val
       of node before modification */
    int old_val = root->data;
 
    /* Recursively call the function for left tree and
       right tree and store the sum as the new val of the node */
    root->data = sumTree(root->left) + sumTree(root->right);
 
    /* Return the sum of values of nodes in left and
       right subtrees and old_value of this node */
    return root->data + old_val;
}
 
/* Inorder traversal for printing the output */
void inorder(node *root)
{
    if(root==NULL)
        return;
    inorder(root->left);
    cout<<root->data<<" ";
    inorder(root->right);
}
 
int main()
{
    node *root = newNode(10);
    root->left = newNode(-2);
    root->right = newNode(6);
    root->left->left = newNode(8);
    root->left->right = newNode(-4);
    root->right->left = newNode(7);
    root->right->right = newNode(5);
 
    cout<<"Given Tree"<<"\n";
    inorder(root);
    cout<<"\n";
 
    sumTree(root);
 
    cout<<"Sum Tree"<<"\n";
    inorder(root);
    cout<<"\n";
 
    return 0;
}
Output:
Given Tree
8 -2 -4 10 7 6 5 
 
Sum Tree
0 4 0 20 0 12 0