Change a Binary Tree so that every node stores sum of all nodes in left subtree | Python3 program to store sum of nodes in left subtree in every node Binary Tree Node utility that allocates a new Node with the given key ; Construct to create a new 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 ; Driver Code ; Let us con below tree 1 / \ 2 3 / \ \ 4 5 6
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def updatetree ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT return root . data NEW_LINE DEDENT leftsum = updatetree ( root . left ) NEW_LINE rightsum = updatetree ( root . right ) NEW_LINE root . data += leftsum NEW_LINE return root . data + rightsum NEW_LINE DEDENT def inorder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE inorder ( node . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . right = newNode ( 6 ) NEW_LINE updatetree ( root ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree ▁ is " ) NEW_LINE inorder ( root ) NEW_LINE DEDENT