![]() |
VOOZH | about |
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:
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:
Below is the implementation of the above approach:
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)