Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to convert a binary tree such that every node stores the sum of all nodes in its right subtree.

For this, we will be provided with a binary tree. Our task is to return another tree where every node must be equal to the sum of the node and its right subtree.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//node structure of tree
struct Node {
   int data;
   Node *left, *right;
};
//creation of a new node
struct Node* createNode(int item){
   Node* temp = new Node;
   temp->data = item;
   temp->left = NULL;
   temp->right = NULL;
   return temp;
}
//creating the new binary tree
int rightsum_tree(Node* root){
   if (!root)
      return 0;
   if (root->left == NULL && root->right == NULL)
      return root->data;
   //changing the values of left/right subtree
   int rightsum = rightsum_tree(root->right);
   int leftsum = rightsum_tree(root->left);
   //adding the sum of right subtree
   root->data += rightsum;
   return root->data + leftsum;
}
//traversing tree in inorder pattern
void inorder(struct Node* node){
   if (node == NULL)
      return;
   inorder(node->left);
   cout << node->data << " ";
   inorder(node->right);
}
int main(){
   struct Node* root = NULL;
   root = createNode(1);
   root->left = createNode(2);
   root->right = createNode(3);
   root->left->left = createNode(4);
   root->left->right = createNode(5);
   root->right->right = createNode(6);
   rightsum_tree(root);
   cout << "Updated Binary Tree :\n";
   inorder(root);
   return 0;
}

Output

Updated Binary Tree :
4 7 5 10 9 6
raja
Published on 02-Jan-2020 10:16:27
Advertisements