Convert a given tree to its Sum Tree - GeeksforGeeks

08 Sep, 2021
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
Solution: Do a traversal of the given tree. In the traversal, store the old value of the current node, recursively call for left and right subtrees 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 subtree rooted with this node). 
C++
C
Java
Python3
C#
Javascript
// C++ program to convert a tree into its sum tree#include <bits/stdc++.h>using namespace std; /* A tree node structure */class node{    public:int data;node *left;node *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 treeint toSumTree(node *Node){    // Base case    if(Node == NULL)    return 0;     // Store the old value    int old_val = Node->data;     // Recursively call for left and    // right subtrees and store the sum as    // old value of this node    Node->data = toSumTree(Node->left) + toSumTree(Node->right);     // Return the sum of values of nodes    // in left and right subtrees and    // old_value of this node    return Node->data + old_val;} // A utility function to print// inorder traversal of a Binary Treevoid printInorder(node* Node){    if (Node == NULL)        return;    printInorder(Node->left);    cout<<" "<<Node->data;    printInorder(Node->right);} /* Utility function to create a new Binary Tree node */node* newNode(int data){    node *temp = new node;    temp->data = data;    temp->left = NULL;    temp->right = NULL;         return temp;} /* Driver code */int main(){    node *root = NULL;    int x;         /* Constructing tree given in the above figure */    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);         toSumTree(root);         // Print inorder traversal of the converted    // tree to test result of toSumTree()    cout<<"Inorder Traversal of the resultant tree is: \n";    printInorder(root);    return 0;} // This code is contributed by rathbhupendra
#include<stdio.h> /* A tree node structure */struct node{  int data;  struct node *left;  struct node *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 treeint toSumTree(struct node *node){    // Base case    if(node == NULL)      return 0;     // Store the old value    int old_val = node->data;     // Recursively call for left and right subtrees and store the sum as    // new value of this node    node->data = toSumTree(node->left) + toSumTree(node->right);     // Return the sum of values of nodes in left and right subtrees and    // old_value of this node    return node->data + old_val;} // A utility function to print inorder traversal of a Binary Treevoid printInorder(struct node* node){     if (node == NULL)          return;     printInorder(node->left);     printf("%d ", node->data);     printInorder(node->right);} /* Utility function to create a new Binary Tree node */struct node* newNode(int data){  struct node *temp = new struct node;  temp->data = data;  temp->left = NULL;  temp->right = NULL;   return temp;} /* Driver function to test above functions */int main(){  struct node *root = NULL;  int x;   /* Constructing tree given in the above figure */  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);   toSumTree(root);   // Print inorder traversal of the converted tree to test result of toSumTree()  printf("Inorder Traversal of the resultant tree is: \n");  printInorder(root);   getchar();  return 0;}
// Java program to convert a tree into its sum tree  // A binary tree nodeclass Node{    int data;    Node left, right;      Node(int item)    {        data = item;        left = right = null;    }}  class BinaryTree{    Node root;      // 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 toSumTree(Node node)    {        // Base case        if (node == null)            return 0;          // Store the old value        int old_val = node.data;          // Recursively call for left and right subtrees and store the sum        // as new value of this node        node.data = toSumTree(node.left) + toSumTree(node.right);          // Return the sum of values of nodes in left and right subtrees        // and old_value of this node        return node.data + old_val;    }      // A utility function to print inorder traversal of a Binary Tree    void printInorder(Node node)    {        if (node == null)            return;        printInorder(node.left);        System.out.print(node.data + " ");        printInorder(node.right);    }      /* Driver function to test above functions */    public static void main(String args[])    {        BinaryTree tree = new BinaryTree();          /* Constructing tree given in the above figure */        tree.root = new Node(10);        tree.root.left = new Node(-2);        tree.root.right = new Node(6);        tree.root.left.left = new Node(8);        tree.root.left.right = new Node(-4);        tree.root.right.left = new Node(7);        tree.root.right.right = new Node(5);          tree.toSumTree(tree.root);          // Print inorder traversal of the converted tree to test result        // of toSumTree()        System.out.println("Inorder Traversal of the resultant tree is:");        tree.printInorder(tree.root);    }} // This code has been contributed by Mayank Jaiswal
# Python3 program to convert a tree# into its sum tree # Node definitionclass node:         def __init__(self, data):        self.left = None        self.right = None        self.data = data # Convert a given tree to a tree where# every node contains sum of values of# nodes in left and right subtrees# in the original treedef toSumTree(Node) :         # Base case    if(Node == None) :        return 0     # Store the old value    old_val = Node.data     # Recursively call for left and    # right subtrees and store the sum as    # new value of this node    Node.data = toSumTree(Node.left) + \                toSumTree(Node.right)     # Return the sum of values of nodes    # in left and right subtrees and    # old_value of this node    return Node.data + old_val # A utility function to print# inorder traversal of a Binary Treedef printInorder(Node) :    if (Node == None) :        return    printInorder(Node.left)    print(Node.data, end = " ")    printInorder(Node.right)     # Utility function to create a new Binary Tree nodedef newNode(data) :    temp = node(0)    temp.data = data    temp.left = None    temp.right = None         return temp # Driver Codeif __name__ == "__main__":    root = None    x = 0         # Constructing tree given in the above figure    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)         toSumTree(root)         # Print inorder traversal of the converted    # tree to test result of toSumTree()    print("Inorder Traversal of the resultant tree is: ")    printInorder(root) # This code is contributed by Arnab Kundu
// C# program to convert a tree// into its sum treeusing System; // A binary tree nodepublic class Node{    public int data;    public Node left, right;     public Node(int item)    {        data = item;        left = right = null;    }} class GFG{public Node root; // Convert a given tree to a tree where// every node contains sum of values of// nodes in left and right subtrees in// the original treepublic virtual int toSumTree(Node node){    // Base case    if (node == null)    {        return 0;    }     // Store the old value    int old_val = node.data;     // Recursively call for left and    // right subtrees and store the sum    // as new value of this node    node.data = toSumTree(node.left) +                toSumTree(node.right);     // Return the sum of values of nodes    // in left and right subtrees old_value    // of this node    return node.data + old_val;} // A utility function to print// inorder traversal of a Binary Treepublic virtual void printInorder(Node node){    if (node == null)    {        return;    }    printInorder(node.left);    Console.Write(node.data + " ");    printInorder(node.right);} // Driver Codepublic static void Main(string[] args){    GFG tree = new GFG();     /* Constructing tree given in       the above figure */    tree.root = new Node(10);    tree.root.left = new Node(-2);    tree.root.right = new Node(6);    tree.root.left.left = new Node(8);    tree.root.left.right = new Node(-4);    tree.root.right.left = new Node(7);    tree.root.right.right = new Node(5);     tree.toSumTree(tree.root);     // Print inorder traversal of the    // converted tree to test result of toSumTree()    Console.WriteLine("Inorder Traversal of " +                     "the resultant tree is:");    tree.printInorder(tree.root);}} // This code is contributed by Shrikant13
<script>  // JavaScript program to convert a tree// into its sum tree // A binary tree nodeclass Node{    constructor(item)    {        this.data = item;        this.left = null;        this.right = null;    }}  var root = null; // Convert a given tree to a tree where// every node contains sum of values of// nodes in left and right subtrees in// the original treefunction toSumTree(node){    // Base case    if (node == null)    {        return 0;    }     // Store the old value    var old_val = node.data;     // Recursively call for left and    // right subtrees and store the sum    // as new value of this node    node.data = toSumTree(node.left) +                toSumTree(node.right);     // Return the sum of values of nodes    // in left and right subtrees old_value    // of this node    return node.data + old_val;} // A utility function to print// inorder traversal of a Binary Treefunction printInorder(node){    if (node == null)    {        return;    }    printInorder(node.left);    document.write(node.data + " ");    printInorder(node.right);} // Driver Code /* Constructing tree given in   the above figure */root = new Node(10);root.left = new Node(-2);root.right = new Node(6);root.left.left = new Node(8);root.left.right = new Node(-4);root.right.left = new Node(7);root.right.right = new Node(5);toSumTree(root);// Print inorder traversal of the// converted tree to test result of toSumTree()document.write("Inorder Traversal of " +                 "the resultant tree is:<br>");printInorder(root);  </script>
Output:  
Inorder Traversal of the resultant tree is:
0 4 0 20 0 12 0
Time Complexity: The solution involves a simple traversal of the given tree. So the time complexity is O(n) where n is the number of nodes in the given Binary Tree.
YouTubeGeeksforGeeks502K subscribersConvert a given tree to its Sum Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:05•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=UQfr5cNnvzA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
shrikanth13
_Gaurav_Tiwari
rathbhupendra
andrew1234
anku25475
rutvik_56
arorakashish0911
Amazon
Microsoft
Samsung
Tree
Amazon
Microsoft
Samsung
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not