text: Change a Binary Tree so that every node stores sum of all nodes in left subtree | C program to store sum of nodes in left subtree in every node ; A tree node ; Function to modify a Binary Tree so that every node stores sum of values in its left child including its own value ; Base cases ; Update left and right subtrees ; Add leftsum to current node ; Return sum of values under root ; Utility function to do inorder traversal ; Utility function to create a new node ; Driver program ; Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; int updatetree ( node * root ) { if ( ! root ) return 0 ; if ( root -> left == NULL && root -> right == NULL ) return root -> data ; int leftsum = updatetree ( root -> left ) ; int rightsum = updatetree ( root -> right ) ; root -> data += leftsum ; return root -> data + rightsum ; } void inorder ( struct node * node ) { if ( node == NULL ) return ; inorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; inorder ( node -> right ) ; } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; updatetree ( root ) ; cout << " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree ▁ is ▁ STRNEWLINE " ; inorder ( root ) ; return 0 ; }