![]() |
VOOZH | about |
Given an arbitrary binary tree, your task is to convert it to a binary tree that holds the Children Sum Property, by incrementing the data values of any node.
Note: The structure of tree can't be changed and the node values can't be decremented. Also, there exist multiple possible answers.
Example:
Input: 50
/ \
7 2
/ \ / \
3 5 1 30
Output: 79
/ \
48 31
/ \ / \
43 5 1 30
Explanation: For every node, now its value is equal to the sum of values of its immediate left and right child. One more possible solution is:50
/ \
19 31
/ \ / \
14 5 1 30
Note: We've discussed the naive approach here Convert an arbitrary Binary Tree to a tree that holds Children Sum Property.
In this article, we've discussed an optimized approach to solve the problem, that works in linear time.
Approach:
In the naive approach, we're firstly converting the children nodes and thereafter updating parent node, due to which we required to update the child nodes again. The idea is to convert the children to the maximum possible value so while moving back there will be no parent having more value than the children, so there will be no extra function to again traverse the subtrees from that node.
Step-by-step approach:
Let us run the algorithm for the given example:
50
/ \
7 2
/ \ / \
3 5 1 30
As sum of children of first node is less than 50 (7 + 2 < 50), update the left node's data (increment 7 to 48).
50
/ \
48 2
/ \ / \
3 5 1 30
Now, sum of children of node with value 48 is less than 48 (3 + 5 < 48), update the left node's data (increment 3 to 43).
50
/ \
48 2
/ \ / \
43 5 1 30
Now, sum of children of node with value 2 is greater than 48 (1 + 30 > 2), update the node's data (increment 2 to 31).
50
/ \
48 31
/ \ / \
43 5 1 30
Now, sum of children of root node is greater than its data i.e. 48 + 31 > 50), update the root's data (increment 50 to 79).
79
/ \
48 31
/ \ / \
43 5 1 30
3 7 5 50 1 2 30 43 48 5 79 1 31 30
Time Complexity: O(n), as we are traversing the tree only once.
Auxiliary Space: O(h), where h is the height of tree.