//-------------------------------------------------------------------------------------------------- // 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(struct node *node) { // Base case if(node == NULL) return 0; // Store the old value int old_val = node->data; // Recursively call for left and right subtrees and store the sum as new value of this node node->data = toSumTree(node->left) + toSumTree(node->right); // Return the sum of values of nodes in left and right subtrees and // old_value of this node return node->data + old_val; }
/* Driver function to test above functions */ int main() { struct node *root = NULL; int x; /* Constructing tree given in the above figure */ root = newNode(10); root->left = newNode(-2); root->right = newNode(6); root->left->left = newNode(8); root->left->right = newNode(-4); root->right->left = newNode(7); root->right->right = newNode(5); root->left->left->left = newNode(1); //root->left->left->right = newNode(2); //root->left->right->left = newNode(3); //root->left->right->right = newNode(4); toSumTree(root); // Print inorder traversal of the converted tree to test result of toSumTree() printf("Inorder Traversal of the resultant tree is: \n"); printInorder(root); getchar(); return 0; }
int toSumTree( Node * root ) { if ( root == nullptr ) { return 0; } //store the previous value int previous_val = root->data; // make current node as sum of left and right node. left nodes will become zero root->data = toSumTree(root->left) + toSumTree(root->right); // Now since each node contains the sum of the left and right sub trees in the original tree. // we will return the sum of old + new value as sum. // Focus on the world original here, and try understanding it from top to bottom. return root->data + previous_val; }
int main() { Node * root = new Node(10); root->left = new Node(-2); root->right = new Node(6); root->left->left = new Node(8); root->left->right = new Node(-4); root->right->left = new Node(7); root->right->right = new Node(5); std::cout << "Inorder traversal of tree:"; inorder(root); std::cout << "\nAfter transforming to sum tree\n"; toSumTree(root); std::cout << "Inorder traversal of tree:"; inorder(root); std::cout << std::endl; return 0; }