Question: Given an arbitrary binary tree, convert it to a binary tree that holds Children Sum Property. You can only increment data values in any node (You cannot change the structure of the tree and cannot decrement the value of any node). For example, the below tree doesn’t hold the children’s sum property, convert it to a tree that holds the property.
/ \ /\
/ \ / \
3 5 1 30
Naive Approach: The Naive Approach is discussed in the Set 1 of this article. Here, we are discussing the optimized approach.
Algorithm: 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.
If the sum of children is less than current node, replace the value of both children with current node’s value.
if(node->left + node->right < node->data) put node->data value in both the child
If the sum of children is greater than or equal to current node, replace the value of current node’s value with sum of children.
if(node->left->data + node->right->data >= node->data) put summation of both child data values in node->data
While traversing back overwrite the existing node values with the sum of left and right child data.
(Note: there will not be any case where the value of node will be greater than the sum of values of their child, because we have given them the maximum possible value).
Follow the steps below to solve the problem:
If root is null then return.
Initialize the variable childSum as 0.
If root has children, then add their value to childSum.
If childSum is greater than equal to root->data, then set root->data as childSum.
Else, if there are children of root, then set their children’s data as root->data.
Call the same function for root->left and root->right.
Initialize the variable totalSumToChangeParent as 0.
If root has children, then add the value of their data to the variable totalSumToChangeParent.
If there is any child of root, then set the value of root as totalSumToChangeParent.
Below is the implementation of the above approach.
Please Login to comment...