Convert a BST to a Binary Tree such that sum of all greater keys is added to every key in C++


In this tutorial, we will be discussing a program to convert a BST to a binary tree such that the sum of all greater keys is added to every key.

For this, we will be provided with a Binary Search tree. Our task is to convert that tree into a binary tree with the sum of all greater keys added to the current key. This will be done by the reverse in order of the given BST along with having the sum of all the previous elements and finally adding it to the current element.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//node structure of BST
struct node{
   int key;
   struct node* left;
   struct node* right;
};
//creating new node with no child
struct node* newNode(int key){
   struct node* node = (struct node*)malloc(sizeof(struct node));
   node->key = key;
   node->left = NULL;
   node->right = NULL;
   return (node);
}
//traversing BST in reverse inorder and adding sum
void reverse_BST(struct node *root, int *sum_ptr){
   if (root == NULL)
      return;
   reverse_BST(root->right, sum_ptr);
   //adding elements along the way
   *sum_ptr = *sum_ptr + root->key;
   root->key = *sum_ptr;
   reverse_BST(root->left, sum_ptr);
}
//Using sum and updating the values
void change_greater(struct node *root){
   int sum = 0;
   reverse_BST(root, &sum);
}
//printing inorder traversal
void printInorder(struct node* node){
   if (node == NULL)
      return;
   printInorder(node->left);
   cout << node->key << " " ;
   printInorder(node->right);
}
int main(){
   node *root = newNode(5);
   root->left = newNode(2);
   root->right = newNode(13);
   cout << "Given Tree :" << endl;
   printInorder(root);
   change_greater(root);
   cout << endl;
   cout << "Modified Tree :" << endl;
   printInorder(root);
   return 0;
}

Output

Given Tree :
2 5 13
Modified Tree :
20 18 13

Updated on: 02-Jan-2020

46 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements