#include <iostream>
#include <iomanip>
#include <conio.h>
/*
http://www.geeksforgeeks.org/convert-bst-to-a-binary-tree/
Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
Given a Binary Search Tree (BST), convert it to a Binary Tree such that every key of the
original BST is changed to key plus sum of all greater keys in BST.
Examples:
Input: Root of following BST
5
/ \\
2 13
Output: The given BST is converted to following Binary Tree
18
/ \\
20 13
Algorithm:
- start with right most node which wil be the greater of all
- maintain a sum of all the visited nodes so far
- do reverse inorder and for every node, replace it with the node\'s data
+ sum so far
*/
struct Node
{
Node(int x):data(x), left(0), right(0){}
int data;
Node* left, *right;
};
/*
display the contents of the tree in inorder traversal
*/
void display(Node* root)
{
if(root->left != NULL)
display(root->left);
std::cout << root->data << std::endl;
if(root->right != NULL)
display(root->right);
}
/*
pass in the root of the binary search tree and get it converted to a BT
as per above conditions
reset sum_so_far to 0 when calling for the first time
*/
int sum_so_far = 0;
void convert_bst_to_bt_helper(Node* root)
{
if(root->right != NULL)
convert_bst_to_bt_helper(root->right);
root->data += sum_so_far;
sum_so_far = root->data;
if(root->left != NULL)
convert_bst_to_bt_helper(root->left);
}
void convert_bst_to_bt(Node* root)
{
std::cout << "pre conversion " << std::endl;
display(root);
sum_so_far = 0;
convert_bst_to_bt_helper(root);
std::cout << "post conversion " << std::endl;
display(root);
}
void testA()
{
Node* root = new Node(2);
root->left = new Node(1);
root->right = new Node(3);
convert_bst_to_bt(root);
}
void testB()
{
Node* root = new Node(4);
root->left = new Node(3);
root->right = new Node(7);
root->left->left = new Node(1);
root->right->left = new Node(5);
root->right->right = new Node(8);
root->right->left->right = new Node(6);
root->right->right->right = new Node(10);
root->right->right->right->left = new Node(9);
convert_bst_to_bt(root);
}
void testC()
{
Node* root = new Node(5);
root->left = new Node(2);
root->right = new Node(13);
convert_bst_to_bt(root);
}
int tests()
{
testA();
testB();
testC();
}
int main()
{
tests();
getch();
}
Yet another blog from yet another software engineer - a collection of my thoughts and some snippets of code I write (mainly for my later reference). If you find this useful, lets discuss in comments.
January 02, 2013
Convert binary search tree (BST) to a binary tree (BT)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment