Last active
May 26, 2018 23:46
-
-
Save thmain/f1d6a9fa036e6f59fd00 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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