Convert an arbitrary Binary Tree to a tree that holds Children Sum Property in C++


In this tutorial, we will be discussing a program to convert an arbitrary binary tree to a tree that holds children sum property.

For this we will be provided with a binary tree. Our task is to convert it into the binary tree that follows the children sum property. But the restriction is that we can only increment the values present in the nodes, neither can change the structure of the tree or decrement values in the node.

Example

 Live Demo

#include<iostream>
#include<bits/stdc++.h>
using namespace std;
//node structure for binary tree
class node{
   public:
   int data;
   node* left;
   node* right;
   //creation of new node
   node(int data){
      this->data = data;
      this->left = NULL;
      this->right = NULL;
   }
};
//incrementing left subtree
void increment(node* node, int diff);
//main function converting the tree
void convert_Btree(node* node){
   int left_data = 0, right_data = 0, diff;
   //returning true in case of root
   //or leaf node
   if (node == NULL || (node->left == NULL &&
   node->right == NULL))
   return;
   else {
      //converting left and right subtrees
      convert_Btree(node->left);
      convert_Btree(node->right);
      if (node->left != NULL)
         left_data = node->left->data;
      if (node->right != NULL)
         right_data = node->right->data;
      //getting children sum
      diff = left_data + right_data - node->data;
      //if children sum is greater than node data
      if (diff > 0)
         node->data = node->data + diff;
      if (diff > 0)
         increment(node, -diff);
   }
}
//incrementing the node value
void increment(node* node, int diff){
   if(node->left != NULL) {
      node->left->data = node->left->data + diff;
      //moving recursively in the tree
      increment(node->left, diff);
   }
   else if (node->right != NULL) {
      node->right->data = node->right->data + diff;
      increment(node->right, diff);
   }
}
//printing inorder traversal
void printInorder(node* node){
   if (node == NULL)
      return;
   printInorder(node->left);
   cout<<node->data<<" ";
   printInorder(node->right);
}
int main(){
   node *root = new node(50);
   root->left = new node(7);
   root->right = new node(2);
   root->left->left = new node(3);
   root->left->right = new node(5);
   root->right->left = new node(1);
   root->right->right = new node(30);
   cout << "Before conversion: " << endl;
   printInorder(root);
   convert_Btree(root);
   cout << "\nAfter conversion: " << endl;
   printInorder(root);
   return 0;
}

OUTPUT

Before conversion:
3 7 5 50 1 2 30
After conversion:
14 19 5 50 1 31 30

Updated on: 16-Jan-2020

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements