Write an efficient algorithm to fix the children-sum property in a given binary tree. The only operation allowed is an increment operation on the node’s value

For a tree to satisfy the children-sum property, each node’s value should be equal to the sum of values at its left and right subtree. The value of an empty node is considered as 0.

For example, the binary tree to the left below does not hold the children-sum property. It should be converted to a binary tree to the right that has that property.
Binary Tree - Children Sum Property

The idea is to traverse the binary tree in a preorder fashion, i.e., fix the left and right subtree to hold the children-sum property before processing the node. Then for each node, calculate the difference between the root and its children.

Here’s a dry run of the algorithm on the above example.
1. Fix the left subtree.
Fixing Children Sum Property - Step 1
2. Fix the right subtree.
Fixing Children Sum Property - Step 2
3. Fix the root by updating the left child by the difference.
Fixing Children Sum Property - Step 3
4. Fix the left subtree again.
Fixing Children Sum Property - Step 4

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

C++

Download   Run Code

Output:

25 12 7 5 13 6 7

Java

Download   Run Code

Output:

25 12 7 5 13 6 7

Python

Download   Run Code

Output:

25 12 7 5 13 6 7

Download   Run Code
Output:

25 12 7 5 13 6 7

Download   Run Code
Output:

25 12 7 5 13 6 7

Download   Run Code
Output:

25 12 7 5 13 6 7

The time complexity of the above solution is O(n2), where n is the total number of nodes in the binary tree. The auxiliary space used by the program is O(h) for the call stack, where h is the height of the tree. The worst-case happens for a skewed tree whose nodes are in decreasing order from root to leaf.

We can solve the problem in O(1) time. The idea is to fix the children-sum property for each node before processing its left and right subtree. After processing the left and right subtree, update the node again with the sum of the left and right child’s data.
The children-sum property can be fixed for a node by either updating the left or the right subtree with the difference between the root and its children. The algorithm can be implemented as follows in C++, Java, and Python:

C++

Download   Run Code

Output:

28 15 10 5 13 6 7

Java

Download   Run Code

Output:

28 15 10 5 13 6 7

Python

Download   Run Code

Output:

28 15 10 5 13 6 7

Download   Run Code
Output:

28 15 10 5 13 6 7

Download   Run Code
Output:

28 15 10 5 13 6 7

Download   Run Code
Output:

28 15 10 5 13 6 7

The above solution works in linear time. Although the resulting tree satisfies the children-sum property, the difference of values in the resultant tree with the original tree is not necessarily minimal. The first approach, however, holds the children-sum property by adding the minimal difference to the nodes.
source