Change a Binary Tree so that every node stores sum of all nodes in left subtree | Java 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
class GfG { static class node { int data ; node left , right ; } static int updatetree ( node root ) { if ( root == null ) 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 ; } static void inorder ( node node ) { if ( node == null ) return ; inorder ( node . left ) ; System . out . print ( node . data + " ▁ " ) ; inorder ( node . right ) ; } static node newNode ( int data ) { node node = new node ( ) ; node . data = data ; node . left = null ; node . right = null ; return ( node ) ; } public static void main ( String [ ] args ) { 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 ) ; System . out . println ( " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree ▁ is " ) ; inorder ( root ) ; } }