Given a binary tree, in-place replace each node’s value to the sum of all elements present in its left and right subtree. You may assume the value of an empty child node to be 0.

For example,

Sum Tree

Practice this problem

We can easily solve this problem by using recursion. The idea is to recursively convert the left and right subtree before processing a node by traversing the tree in a postorder fashion. Then for each node, update the node’s value to the sum of all elements present in its left and right subtree and return the sum of all elements present in the subtree rooted at the node from the function. The value is calculated at a constant time for each node using the left and right subtree’s return values.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

35 4 0 26 15 0 0 0

Java


Download  Run Code

Output:

35 4 0 26 15 0 0 0

Python


Download  Run Code

Output:

35 4 0 26 15 0 0 0

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.