Created
July 2, 2017 11:59
-
-
Save anil477/2af59456e20dd11496104c2fbc6d89b9 to your computer and use it in GitHub Desktop.
Convert a given tree to its Sum Tree Given a Binary Tree
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
// 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. | |
// http://www.geeksforgeeks.org/convert-a-given-tree-to-sum-tree/ | |
class Node | |
{ | |
int data; | |
Node left, right; | |
Node(int item) | |
{ | |
data = item; | |
left = right = null; | |
} | |
} | |
class BinaryTree | |
{ | |
Node root; | |
// Convert a given tree to a tree where every node contains sum of | |
// values of nodes in left and right subtrees in the original tree | |
int toSumTree(Node node) | |
{ | |
if (node == null) | |
return 0; | |
int ori = node.data; | |
node.data = toSumTree(node.left) + toSumTree(node.right); | |
return (node.data + ori); | |
} | |
// A utility function to print inorder traversal of a Binary Tree | |
void printInorder(Node node) | |
{ | |
if (node == null) | |
return; | |
printInorder(node.left); | |
System.out.print(node.data + " "); | |
printInorder(node.right); | |
} | |
/* Driver function to test above functions */ | |
public static void main(String args[]) | |
{ | |
BinaryTree tree = new BinaryTree(); | |
/* Constructing tree given in the above figure */ | |
tree.root = new Node(10); | |
tree.root.left = new Node(-2); | |
tree.root.right = new Node(6); | |
tree.root.left.left = new Node(8); | |
tree.root.left.right = new Node(-4); | |
tree.root.right.left = new Node(7); | |
tree.root.right.right = new Node(5); | |
tree.toSumTree(tree.root); | |
// Print inorder traversal of the converted tree to test result | |
// of toSumTree() | |
System.out.println("Inorder Traversal of the resultant tree is:"); | |
tree.printInorder(tree.root); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment