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 ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; 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 ; Driver code ; Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left , * right ; node ( int data ) { this -> data = data ; this -> left = NULL ; this -> right = NULL ; } } ; 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 ( node * node ) { if ( node == NULL ) return ; inorder ( node -> left ) ; cout << node -> data << " ▁ " ; inorder ( node -> right ) ; } int main ( ) { struct node * root = new node ( 1 ) ; root -> left = new node ( 2 ) ; root -> right = new node ( 3 ) ; root -> left -> left = new node ( 4 ) ; root -> left -> right = new node ( 5 ) ; root -> right -> right = new node ( 6 ) ; updatetree ( root ) ; cout << " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree ▁ is : ▁ STRNEWLINE " ; inorder ( root ) ; return 0 ; }