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 structure of tree and cannot decrement value of any node).
For example, the below tree doesn’t hold the children sum property, convert it to a tree that holds the property.
50 / \ / \ 7 2 / \ /\ / \ / \ 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
Java Implementation:
static void convertMaxSumTree(Node root){
if(root == null || (root.left == null && root.right == null)) return;
int sum = 0 ;
convertMaxSumTree(root.left);
convertMaxSumTree(root.right);
if(root.left != null){
sum += root.left.data;
}
if(root.right != null)
sum += root.right.data;
int diff = sum - root.data;
if(diff > 0){
root.data += diff;
}else if(diff < 0){
increaseValue(root, -diff);
}
}
private static void increaseValue(Node root, int diff) {
//if(root == null) return;
if(root.left != null)
{
root.left.data += diff;
increaseValue(root.left, diff);
}else if(root.right != null)
{
root.right.data += diff;
increaseValue(root.right, diff);
}
}