> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/trees/convert-a-given-tree-to-its-sum-tree.md).

# Convert a given tree to its Sum Tree

Given a Binary Tree where each node has positive and negative values. Convert this to a tree where each node contains the sum of the left and right sub trees in the original tree. The values of leaf nodes are changed to 0.

For example, the following tree

```
                  10
               /      \
             -2        6
           /   \      /  \ 
         8     -4    7    5
```

should be changed to

```
                 20(4-2+12+6)
               /      \
         4(8-4)      12(7+5)
           /   \      /  \ 
         0      0    0    0
```

```java
class Tree {
    public int helper(Node node) {
        if (node == null)
            return 0;
        if (node.left == null && node.right == null) {
            int sum = node.data;
            node.data = 0;
            return sum;
        }
        int leftSum = helper(node.left);
        int rightSum = helper(node.right);
        int sum = leftSum + rightSum + node.data;
        node.data = leftSum + rightSum;
        return sum;
    }

    public void toSumTree(Node root) {
        helper(root);
    }
}
```
