VOOZH about

URL: https://www.geeksforgeeks.org/dsa/create-binary-tree-with-nodes-as-cumulative-sum-of-children/

⇱ Create Binary Tree with Nodes as Cumulative sum of children - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Create Binary Tree with Nodes as Cumulative sum of children

Last Updated : 23 Jul, 2025

Given a root of a Binary Tree, the task is to update each of its nodes with the sum of all the nodes below it (from its left and right subtree), inclusive of the current Node.

Example:

👁 updateSum
Example Test Case-I


Approach:

The idea is to simply traverse through left and right subtree, and calculate sum of Left Subtree & Right Subtree, and then update the current node with the sum returned from the left subtree and the right subtree + its own value.

Our base case would be the leaf node (The node which doesn't have ANY child).

Here's how to do this step-by-step:

  • Traverse till leaf node (either left of right)
  • Once you encounter a leaf node, the base case will be executed, and it will return the leaf node's value
  • Calculate sum of left subtree and right subtree, and add both of them (left Subtree + right Subtree's values)
  • The only catch we need to handle when our input tree is a binary tree(not necessarily a FULL Binary tree) is that, we need to check if the child exists before moving on to it.
  • Update the current node's value with the sum calculated in previous step.

Below is the implementation of the above approach:


Output
Inorder Before updating the Sum for every Node :
6 4 2 5 1 
Inorder After updating the Sum for every Node :
6 10 17 5 18 

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment