#include <iostream>

using namespace std;

// structure to store a Binary Search Tree node

struct Node {

int data;

Node *left, *right;

};

// Function to create a new binary tree node having given

Node* newNode(int key)

{

Node* node = new Node;

node->data = key;

node->left = node->right = nullptr;

return node;

}

// Function to perform in-order traversal of the tree

void inorder(Node* root)

{

if (root == nullptr)

return;

inorder(root->left);

cout << root->data << ” “;

inorder(root->right);

}

// Recursive function to insert an key into

Node* insert(Node* root, int key)

{

// if the root is null, create a new node an return it

if (root == nullptr)

return newNode(key);

// if given key is less than the root node, recuse for left subtree

if (key < root->data)

root->left = insert(root->left, key);

// if given key is more than the root node, recuse for right subtree

else

root->right = insert(root->right, key);

return root;

}

// Helper function to return of all nodes present in a binary tree

int findSum(Node* root)

{

if (root == nullptr)

return 0;

return root->data + findSum(root->left) + findSum(root->right);

}

// Function to modify the BST such that every key is updated to

// contain sum of all

void (Node* root, int &sum)

{

// base case

if (root == nullptr)

return;

// update the left subtree

update(root->left, sum);

// modify the sum to contain sum of all greater keys

sum = sum root->data;

// update the root to contain sum of all greater keys

root->data += sum;

// update the right subtree

update(root->right, sum);

}

// main function

int main()

{

Node* root = nullptr;

/* Construct below tree

5

/

/

3       8

/      /

/      /

2     4 6       */

int keys[] = { 5, 3, 2, 4, 6, 8, 10 };

int n = sizeof(keys)/sizeof(keys[0]);

for (int key : keys)

root = insert(root, key);

int sum = findSum(root);

update(root, sum);

inorder(root);

return 0;

}