Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active May 26, 2018
Embed
What would you like to do?
public class TreeToSumTree {
static Node newRoot;
public int SumTree(Node root){
if(root!=null){
int left = SumTree(root.left);//take the left tree sum
int right = SumTree(root.right);//take the right tree sum
int retData = root.data+left+right; // return data left+right+root
root.data = left+right; //update the root with left + right
newRoot = root; //update the new root
return retData; //return
}
return 0;
}
public void display(Node root){
if(root!=null){
display(root.left);
System.out.print(root.data + " " );
display(root.right);
}
}
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: ");
t.display(root);
System.out.print("\nSum tree: ");
t.SumTree(root);
//Print the new tree
t.display(newRoot);
}
}
class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment