![]() |
VOOZH | about |
Given an arbitrary binary tree, your task is to convert it to a binary tree that holds Children Sum Property, by incrementing the data values of any node.
Note: The structure of the 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: 50
/ \
19 31
/ \ / \
14 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:79
/ \
48 31
/ \ / \
43 5 1 30
Table of Content
The idea is to traverse the given tree in post order to firstly convert the left and right children to hold the children sum property and then change the parent node.
After converting the child nodes, find the difference diff between node's data and sum of children nodes i.e. diff = node’s children sum - node’s data.
There are three possibilities:
Incrementing a child changes the subtree’s children sum property so we need to change left subtree also. So we recursively increment the left child. If left child is empty then we recursively call increment() for right child.
Let us run the algorithm for the given example:
50
/ \
7 2
/ \ / \
3 5 1 30
First convert the left subtree (increment 7 to 8).
50
/ \
8 2
/ \ / \
3 5 1 30
Then convert the right subtree (increment 2 to 31)
50
/ \
8 31
/ \ / \
3 5 1 30
Now convert the root, we have to increment left subtree for converting the root.
50
/ \
19 31
/ \ / \
14 5 1 30
Please note the last step – we have incremented 8 to 19, and to fix the subtree we have incremented 3 to 14.
3 7 5 50 1 2 30 14 19 5 50 1 31 30
Time Complexity: O(n ^ 2), worst case complexity is for a skewed tree such that nodes are in decreasing order from root to leaf.
AuxiliarySpace : O(h) where h is the height of the binary tree.
The idea is to modify the children nodes in top-down fashion while fix the children sum property in bottom-up fashion. To make sure that the parent's node data is not greater than sum of children nodes data, update the child nodes while going down the tree. And while returning sum the child nodes data and update the parent node's data accordingly.
Consider the following example:
50
/ \
7 2
/ \ / \
3 5 1 30
Here, the issue is having shortage while summing, like 1 + 30 =31 then 3 + 5 = 8 => 31+8 =39, but u cannot decrement 50 to 39 as per rule.
3 7 5 50 1 2 30 43 48 5 79 1 31 30