Convert binary tree to its Sum tree

Objective: Given a binary tree, write an algorithm to convert it into its Sum tree.

What is Sum tree: Sum tree of a binary tree, is a tree where each node in the converted tree will contains the sum of the left and right sub trees in the original tree.



Convert binary tree to its Sum tree.


  1. Recursively calculate the left sum from left sum tree.
  2. Recursively calculate the right sum from right tree.
  3. prepare the return + left sum + right sum.
  4. Update the root data as = left sum + right sum.
  5. update the newRoot = root.
  6. See the code for better understanding.

Complete Code:

public class TreeToSumTree {
static Node newRoot;
public int SumTree(Node root){
int left = SumTree(root.left);//take the left tree sum
int right = SumTree(root.right);//take the right tree sum
int retData =; // return data left+right+root = left+right; //update the root with left + right
newRoot = root; //update the new root
return retData; //return
return 0;
public void display(Node root){
System.out.print( + " " );
public static void main(String args[]){
Node root = new Node(5);
root.left = new Node(1);
root.right = new Node(3);
root.left.left = new Node(2);
root.left.right = new Node(4);
root.right.left = new Node(6);
root.right.right = new Node(10 );
TreeToSumTree t = new TreeToSumTree();
System.out.print("Original Tree: ");
System.out.print("\nSum tree: ");
//Print the new tree
class Node{
int data;
Node left;
Node right;
public Node(int data){ = data;


Original Tree: -2  -1  4  5  -6  3  10
Sum tree: 0  2  0  8  0  4  0

2 thoughts on “Convert binary tree to its Sum tree”

  1. why do u need to set the newRoot in line13? you are not changing any node pointers in the SumTree method. looks like an unnecessary line of code that really does nothing.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.