> 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);
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mayanktyagi3111.gitbook.io/interview-prep/trees/convert-a-given-tree-to-its-sum-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
