#include <bits/stdc++.h>
using namespace std;
// tree node is defined
class TreeNode
{
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int data)
{
val = data;
left = NULL;
right = NULL;
}
};
// inorder traversal for tree
void inorder(TreeNode *root)
{
if (!root)
return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
// Recursive function to transform a BST to sum tree.
// do a reverse inorder traversal for the BST
void transformToGreaterSumTreeRecur(TreeNode *root, int &sum)
{
// Base case
if (!root)
return;
// Recur for right subtree first as
// it's reverse inorder traversal
transformToGreaterSumTreeRecur(root->right, sum);
// store the previous sum and update sum
int prevSum = sum;
sum = sum + root->val;
// Store old sum in the current node which is sum
// of the right subtree nodes(nodes greater than the root)
root->val = prevSum;
// Recur for left subtree now
transformToGreaterSumTreeRecur(root->left, sum);
}
void transformToGreaterSumTree(TreeNode *root)
{
// initially sum is 0
int sum = 0;
transformToGreaterSumTreeRecur(root, sum);
}
int main()
{
// Tree built as per example
TreeNode *root = new TreeNode(10);
root->left = new TreeNode(7);
root->right = new TreeNode(15);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(9);
root->right->left = new TreeNode(13);
root->right->right = new TreeNode(18);
cout << "Inorder Traversal of the given tree\n";
inorder(root);
cout << "\nconverting to greater Sum tree\n";
transformToGreaterSumTree(root);
cout << "Conversion completed\n";
cout << "Inorder Traversal of transformed greater sum tree:\n";
inorder(root);
return 0;
}
Output
Inorder Traversal of the given tree
4 7 9 10 13 15 18
converting to greater Sum tree
Conversion completed
Inorder Traversal of transformed greater sum tree:
72 65 56 46 33 18 0
0 Comments