Convert a given tree to its Sum Tree | C ++ program to convert a tree into its sum tree ; A tree node structure ; 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 ; Base case ; Store the old value ; Recursively call for left and right subtrees and store the sum as new value of this node ; Return the sum of values of nodes in left and right subtrees and old_value of this node ; A utility function to print inorder traversal of a Binary Tree ; Utility function to create a new Binary Tree node ; Driver code ; Constructing tree given in the above figure ; Print inorder traversal of the converted tree to test result of toSumTree ( )
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; } ; int toSumTree ( node * Node ) { if ( Node == NULL ) return 0 ; int old_val = Node -> data ; Node -> data = toSumTree ( Node -> left ) + toSumTree ( Node -> right ) ; return Node -> data + old_val ; } void printInorder ( node * Node ) { if ( Node == NULL ) return ; printInorder ( Node -> left ) ; cout << " ▁ " << Node -> data ; printInorder ( Node -> right ) ; } node * newNode ( int data ) { node * temp = new node ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } int main ( ) { node * root = NULL ; int x ; 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 ) ; cout << " Inorder ▁ Traversal ▁ of ▁ the ▁ resultant ▁ tree ▁ is : ▁ STRNEWLINE " ; printInorder ( root ) ; return 0 ; }