Change a Binary Tree so that every node stores sum of all nodes in left subtree

Given a Binary Tree, change the value in each node to sum of all the values in the nodes in the left subtree including its own.

Examples:

Input : 
     1
   /   \
  2     3

Output :
    3
  /   \
 2     3


Input
       1
      / \
     2   3
    / \   \
   4   5   6
Output:
      12
     / \
    6   3
   / \   \
  4   5   6
class Solution {
    public int convertToLeftSumTree(Node node) {
        if (node == null)
            return 0;
        if (node.left == null && node.right == null) 
            return node.data;
        int left = convertToLeftSumTree(node.left);
        int right = convertToLeftSumTree(node.right);
        node.data += left;
        return node.data + right;
    }
}

Last updated