Example
Input Tree
A
/ \
B C
/ \ \
D E F
Output Tree
A---> NULL
/ \
B--> C--> NULL
/ \ \
D--> E--> F--> NULL
Method 1 (Extend Level Order Traversal or BFS)
Input Tree
A
/ \
B C
/ \ \
D E F
Output Tree
A---> NULL
/ \
B--> C--> NULL
/ \ \
D--> E--> F--> NULL
2 / \ 1 3is changed to…
2
/ \
2 3
/ /
1 3
/
1
And the tree 1
/ \
2 3
/ \
4 5
is changed to 1
/ \
1 3
/ /
2 3
/ \
2 5
/ /
4 5
/
4
50
/ \
/ \
7 2
/ \ /\
/ \ / \
3 5 1 30
50
/ \
/ \
19 31
/ \ / \
/ \ / \
14 5 1 30
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);
}
}