VOOZH about

URL: https://www.geeksforgeeks.org/dsa/change-a-binary-tree-so-that-every-node-stores-sum-of-all-nodes-in-left-subtree/

⇱ Change a Binary Tree so that every node stores sum of all nodes in left subtree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Change a Binary Tree so that every node stores sum of all nodes in left subtree

Last Updated : 16 Aug, 2022

Given a Binary Tree, change the value in each node to sum of all the values in the nodes in the left subtree including its own.

Examples: 

Input : 
 1
 / \
 2 3

Output :
 3
 / \
 2 3


Input
 1
 / \
 2 3
 / \ \
 4 5 6
Output:
 12
 / \
 6 3
 / \ \
 4 5 6

We strongly recommend you to minimize your browser and try this yourself first.
The idea is to traverse the given tree in bottom up manner. For every node, recursively compute sum of nodes in left and right subtrees. Add sum of nodes in left subtree to current node and return sum of nodes under current subtree.

Below is the implementation of above idea. 


Output
Inorder traversal of the modified tree is: 
4 6 5 12 3 6 

Time Complexity: O(n)

Auxiliary space: O(n) for implicit call stack as using recursion

Thanks to Gaurav Ahrirwar for suggesting this solution.

Comment
Article Tags:
Article Tags: