|
| 1 | +/** |
| 2 | + * Convert a given tree to to sum tree. |
| 3 | + * Given : A tree with positive and negative data values. |
| 4 | + * Convert this to a tree where each node contains the sum of the left and right sub trees in the original tree. |
| 5 | + * The values of leaf nodes are changed to 0. |
| 6 | + * 10 20 |
| 7 | + * / \ / \ |
| 8 | + * -2 6 ----> 4 12 |
| 9 | + * / \ / \ / \ / \ |
| 10 | + * 8 -4 7 5 0 0 0 0 |
| 11 | + */ |
| 12 | + |
| 13 | +#include <iostream> |
| 14 | + |
| 15 | +struct Node { |
| 16 | + int data; |
| 17 | + Node * left; |
| 18 | + Node * right; |
| 19 | + Node( int d ) |
| 20 | + : data{ d }, |
| 21 | + left{ nullptr }, |
| 22 | + right{ nullptr } { } |
| 23 | +}; |
| 24 | + |
| 25 | +int toSumTree( Node * root ) |
| 26 | +{ |
| 27 | + if ( root == nullptr ) |
| 28 | + { |
| 29 | + return 0; |
| 30 | + } |
| 31 | + |
| 32 | + //store the previous value |
| 33 | + int previous_val = root->data; |
| 34 | + |
| 35 | + // make current node as sum of left and right node. left nodes will become zero |
| 36 | + root->data = toSumTree(root->left) + toSumTree(root->right); |
| 37 | + |
| 38 | + // Now since each node contains the sum of the left and right sub trees in the original tree. |
| 39 | + // we will return the sum of old + new value as sum. |
| 40 | + // Focus on the world original here, and try understanding it from top to bottom. |
| 41 | + return root->data + previous_val; |
| 42 | +} |
| 43 | + |
| 44 | +void inorder( Node * root ) |
| 45 | +{ |
| 46 | + if ( root ) { |
| 47 | + inorder(root->left); |
| 48 | + std::cout << root->data << " "; |
| 49 | + inorder(root->right); |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | + |
| 54 | +int main() |
| 55 | +{ |
| 56 | + Node * root = new Node(10); |
| 57 | + root->left = new Node(-2); |
| 58 | + root->right = new Node(6); |
| 59 | + root->left->left = new Node(8); |
| 60 | + root->left->right = new Node(-4); |
| 61 | + root->right->left = new Node(7); |
| 62 | + root->right->right = new Node(5); |
| 63 | + std::cout << "Inorder traversal of tree:"; |
| 64 | + inorder(root); |
| 65 | + std::cout << "\nAfter transforming to sum tree\n"; |
| 66 | + toSumTree(root); |
| 67 | + std::cout << "Inorder traversal of tree:"; |
| 68 | + inorder(root); |
| 69 | + std::cout << std::endl; |
| 70 | + return 0; |
| 71 | +} |
0 commit comments