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
Method 1:
Solution: Do reverse In order traversal. Keep track of the sum of nodes visited so far. Let this sum be sum. For every node currently being visited, first add the key of this node to sum, i.e. sum = sum + node->key. Then change the key of current node to sum, i.e., node->key = sum.
When a BST is being traversed in reverse In order, for every key currently being visited, all keys that are already visited are all greater keys.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct node
{
int key;
struct node* left;
struct node* right;
};
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);
}
void addGreaterUtil( struct node *root, int *sum_ptr)
{
if (root == NULL)
return ;
addGreaterUtil(root->right, sum_ptr);
*sum_ptr = *sum_ptr + root->key;
root->key = *sum_ptr;
addGreaterUtil(root->left, sum_ptr);
}
void addGreater( struct node *root)
{
int sum = 0;
addGreaterUtil(root, &sum);
}
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 << "Inorder traversal of the "
<< "given tree" << endl;
printInorder(root);
addGreater(root);
cout << endl;
cout << "Inorder traversal of the "
<< "modified tree" << endl;
printInorder(root);
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
struct node
{
int key;
struct node* left;
struct node* right;
};
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);
}
void addGreaterUtil( struct node *root, int *sum_ptr)
{
if (root == NULL)
return ;
addGreaterUtil(root->right, sum_ptr);
*sum_ptr = *sum_ptr + root->key;
root->key = *sum_ptr;
addGreaterUtil(root->left, sum_ptr);
}
void addGreater( struct node *root)
{
int sum = 0;
addGreaterUtil(root, &sum);
}
void printInorder( struct node* node)
{
if (node == NULL)
return ;
printInorder(node->left);
printf ( "%d " , node->key);
printInorder(node->right);
}
int main()
{
node *root = newNode(5);
root->left = newNode(2);
root->right = newNode(13);
printf ( "Inorder traversal of the given tree\n" );
printInorder(root);
addGreater(root);
printf ( "\nInorder traversal of the modified tree\n" );
printInorder(root);
return 0;
}
|
Java
class Node {
int data;
Node left, right;
Node( int d) {
data = d;
left = right = null ;
}
}
class Sum {
int sum = 0 ;
}
class BinaryTree {
static Node root;
Sum summ = new Sum();
void addGreaterUtil(Node node, Sum sum_ptr) {
if (node == null ) {
return ;
}
addGreaterUtil(node.right, sum_ptr);
sum_ptr.sum = sum_ptr.sum + node.data;
node.data = sum_ptr.sum;
addGreaterUtil(node.left, sum_ptr);
}
Node addGreater(Node node) {
addGreaterUtil(node, summ);
return node;
}
void printInorder(Node node) {
if (node == null ) {
return ;
}
printInorder(node.left);
System.out.print(node.data + " " );
printInorder(node.right);
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new Node( 5 );
tree.root.left = new Node( 2 );
tree.root.right = new Node( 13 );
System.out.println( "Inorder traversal of given tree " );
tree.printInorder(root);
Node node = tree.addGreater(root);
System.out.println( "" );
System.out.println( "Inorder traversal of modified tree " );
tree.printInorder(node);
}
}
|
Python3
class Node:
def __init__( self , data):
self .key = data
self .left = None
self .right = None
def addGreaterUtil(root, sum_ptr):
if root = = None :
return
addGreaterUtil(root.right, sum_ptr)
sum_ptr[ 0 ] = sum_ptr[ 0 ] + root.key
root.key = sum_ptr[ 0 ]
addGreaterUtil(root.left, sum_ptr)
def addGreater(root):
Sum = [ 0 ]
addGreaterUtil(root, Sum )
def printInorder(node):
if node = = None :
return
printInorder(node.left)
print (node.key, end = " " )
printInorder(node.right)
if __name__ = = '__main__' :
root = Node( 5 )
root.left = Node( 2 )
root.right = Node( 13 )
print ( "Inorder traversal of the given tree" )
printInorder(root)
addGreater(root)
print ()
print ( "Inorder traversal of the modified tree" )
printInorder(root)
|
C#
using System;
public class Node
{
public int data;
public Node left, right;
public Node( int d)
{
data = d;
left = right = null ;
}
}
public class Sum
{
public int sum = 0;
}
public class BinaryTree
{
public static Node root;
public Sum summ = new Sum();
public virtual void addGreaterUtil(Node node, Sum sum_ptr)
{
if (node == null )
{
return ;
}
addGreaterUtil(node.right, sum_ptr);
sum_ptr.sum = sum_ptr.sum + node.data;
node.data = sum_ptr.sum;
addGreaterUtil(node.left, sum_ptr);
}
public virtual Node addGreater(Node node)
{
addGreaterUtil(node, summ);
return node;
}
public virtual void printInorder(Node node)
{
if (node == null )
{
return ;
}
printInorder(node.left);
Console.Write(node.data + " " );
printInorder(node.right);
}
public static void Main( string [] args)
{
BinaryTree tree = new BinaryTree();
BinaryTree.root = new Node(5);
BinaryTree.root.left = new Node(2);
BinaryTree.root.right = new Node(13);
Console.WriteLine( "Inorder traversal of given tree " );
tree.printInorder(root);
Node node = tree.addGreater(root);
Console.WriteLine( "" );
Console.WriteLine( "Inorder traversal of modified tree " );
tree.printInorder(node);
}
}
|
Javascript
<script>
class Node
{
constructor(d)
{
this .data = d;
this .left = null ;
this .right = null ;
}
}
class Sum
{
constructor()
{
this .sum = 0;
}
}
var root = null ;
var summ = new Sum();
function addGreaterUtil(node, sum_ptr)
{
if (node == null )
{
return ;
}
addGreaterUtil(node.right, sum_ptr);
sum_ptr.sum = sum_ptr.sum + node.data;
node.data = sum_ptr.sum;
addGreaterUtil(node.left, sum_ptr);
}
function addGreater(node)
{
addGreaterUtil(node, summ);
return node;
}
function printInorder(node)
{
if (node == null )
{
return ;
}
printInorder(node.left);
document.write(node.data + " " );
printInorder(node.right);
}
root = new Node(5);
root.left = new Node(2);
root.right = new Node(13);
document.write( "Inorder traversal of given tree <br>" );
printInorder(root);
var node = addGreater(root);
document.write( "<br>" );
document.write( "Inorder traversal of modified tree <br>" );
printInorder(node);
</script>
|
OutputInorder traversal of the given tree
2 5 13
Inorder traversal of the modified tree
20 18 13
Time Complexity: O(n) where n is the number of nodes in given Binary Search Tree.
The space complexity is O(H), where H is the height of the tree, due to the recursive call stack.
Method 2:
The below method uses the technique of Iteration with the Stack.
Approach:
- First, we initialize an empty stack and set the current node to the root.
- Then, so long as there are unvisited nodes in the stack or the node does not point to null, we push all of the nodes along the path to the rightmost leaf onto the stack.
- . Next, we visit the node on the top of our stack and consider its left subtree.
- Eventually, our stack is empty and the node points to the left null child of the tree’s minimum value node, so the loop terminates.
Below is the implementation of the above approach:
C
#include <stdio.h>
#include <stdlib.h>
#define bool int
struct tNode {
int data;
struct tNode* left;
struct tNode* right;
};
struct sNode {
struct tNode* t;
struct sNode* next;
};
void push( struct sNode** top_ref, struct tNode* t);
struct tNode* pop( struct sNode** top_ref);
bool isEmpty( struct sNode* top);
void inOrder( struct tNode* root)
{
struct tNode* current = root;
struct sNode* s = NULL;
bool done = 0;
while (!done) {
if (current != NULL) {
push(&s, current);
current = current->left;
}
else {
if (!isEmpty(s)) {
current = pop(&s);
printf ( "%d " , current->data);
current = current->right;
}
else
done = 1;
}
}
}
void Greater_BST( struct tNode* root)
{
int sum = 0;
struct sNode* st = NULL;
struct tNode* node = root;
while (!isEmpty(st) || node != NULL) {
while (node != NULL) {
push(&st, node);
node = node->right;
}
node = pop(&st);
sum += node->data;
node->data = sum;
node = node->left;
}
}
void push( struct sNode** top_ref, struct tNode* t)
{
struct sNode* new_tNode
= ( struct sNode*) malloc ( sizeof ( struct sNode));
if (new_tNode == NULL) {
printf ( "Stack Overflow \n" );
getchar ();
exit (0);
}
new_tNode->t = t;
new_tNode->next = (*top_ref);
(*top_ref) = new_tNode;
}
bool isEmpty( struct sNode* top)
{
return (top == NULL) ? 1 : 0;
}
struct tNode* pop( struct sNode** top_ref)
{
struct tNode* res;
struct sNode* top;
top = *top_ref;
res = top->t;
*top_ref = top->next;
free (top);
return res;
}
struct tNode* newtNode( int data)
{
struct tNode* tNode
= ( struct tNode*) malloc ( sizeof ( struct tNode));
tNode->data = data;
tNode->left = NULL;
tNode->right = NULL;
return (tNode);
}
int main()
{
struct tNode* root = newtNode(8);
root->left = newtNode(5);
root->right = newtNode(12);
root->left->left = newtNode(2);
root->left->right = newtNode(7);
root->right->left = newtNode(9);
root->right->right = newtNode(15);
Greater_BST(root);
inOrder(root);
getchar ();
return 0;
}
|
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int data;
Node *left, *right;
};
Node* newNode( int item)
{
Node* temp = new Node();
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
void Greater_BST(Node* root)
{
int sum = 0;
stack<Node*> st;
Node* node = root;
while (!st.empty() || node != NULL ){
while (node != NULL){
st.push(node);
node = node->right;
}
node = st.top();
st.pop();
sum += node->data;
node->data = sum;
node = node->left;
}
}
void inorder(Node* root)
{
if (root != NULL) {
inorder(root->left);
cout << root->data << " " ;
inorder(root->right);
}
}
Node* insert(Node* node, int data)
{
if (node == NULL)
return newNode(data);
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
return node;
}
int main()
{
Node* root = NULL;
root = insert(root, 8);
insert(root, 5);
insert(root, 2);
insert(root, 7);
insert(root, 12);
insert(root, 9);
insert(root, 15);
Greater_BST(root);
inorder(root);
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node left, right;
Node( int d)
{
data = d;
left = right = null ;
}
}
class BinarySearchTree {
Node root;
BinarySearchTree() { root = null ; }
void inorder() { inorderUtil( this .root); }
void inorderUtil(Node node)
{
if (node == null )
return ;
inorderUtil(node.left);
System.out.print(node.data + " " );
inorderUtil(node.right);
}
public void insert( int data)
{
this .root = this .insertRec( this .root, data);
}
Node insertRec(Node node, int data)
{
if (node == null ) {
this .root = new Node(data);
return this .root;
}
if (data <= node.data) {
node.left = this .insertRec(node.left, data);
}
else {
node.right = this .insertRec(node.right, data);
}
return node;
}
void Greater_BST(Node root)
{
int sum = 0 ;
Node node = root;
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || node != null ) {
while (node != null ) {
stack.add(node);
node = node.right;
}
node = stack.pop();
sum += node.data;
node.data = sum;
node = node.left;
}
}
public static void main(String[] args)
{
BinarySearchTree tree = new BinarySearchTree();
tree.insert( 8 );
tree.insert( 5 );
tree.insert( 2 );
tree.insert( 7 );
tree.insert( 12 );
tree.insert( 9 );
tree.insert( 15 );
tree.Greater_BST(tree.root);
tree.inorder();
}
}
|
Python3
class newNode:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def Greater_BST(root):
total = 0
node = root
stack = []
while stack or node is not None :
while node is not None :
stack.append(node)
node = node.right
node = stack.pop()
total + = node.data
node.data = total
node = node.left
def inorder(root):
if root ! = None :
inorder(root.left)
print (root.data, end = " " )
inorder(root.right)
def insert(node, data):
if node = = None :
return newNode(data)
if data < = node.data:
node.left = insert(node.left, data)
else :
node.right = insert(node.right, data)
return node
if __name__ = = '__main__' :
root = None
root = insert(root, 8 )
insert(root, 5 )
insert(root, 2 )
insert(root, 7 )
insert(root, 9 )
insert(root, 12 )
insert(root, 15 )
Greater_BST(root)
inorder(root)
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int data;
public Node left, right;
public Node( int d)
{
data = d;
left = right = null ;
}
}
public class BinarySearchTree {
Node root;
BinarySearchTree() { root = null ; }
void inorder() { inorderUtil( this .root); }
void inorderUtil(Node node)
{
if (node == null )
return ;
inorderUtil(node.left);
Console.Write(node.data + " " );
inorderUtil(node.right);
}
public void insert( int data)
{
this .root = this .insertRec( this .root, data);
}
Node insertRec(Node node, int data)
{
if (node == null ) {
this .root = new Node(data);
return this .root;
}
if (data <= node.data) {
node.left = this .insertRec(node.left, data);
}
else {
node.right = this .insertRec(node.right, data);
}
return node;
}
void Greater_BST(Node root)
{
int sum = 0;
Node node = root;
Stack<Node> stack = new Stack<Node>();
while (stack.Count!=0 || node != null ) {
while (node != null ) {
stack.Push(node);
node = node.right;
}
node = stack.Pop();
sum += node.data;
node.data = sum;
node = node.left;
}
}
public static void Main(String[] args)
{
BinarySearchTree tree = new BinarySearchTree();
tree.insert(8);
tree.insert(5);
tree.insert(2);
tree.insert(7);
tree.insert(12);
tree.insert(9);
tree.insert(15);
tree.Greater_BST(tree.root);
tree.inorder();
}
}
|
Javascript
<script>
class Node {
constructor(d)
{
this .data = d;
this .left = this .right = null ;
}
}
var root = null ;
function inorder() { inorderUtil( this .root); }
function inorderUtil(node)
{
if (node == null )
return ;
inorderUtil(node.left);
document.write(node.data + " " );
inorderUtil(node.right);
}
function insert(data)
{
this .root = this .insertRec( this .root, data);
}
function insertRec(node , data)
{
if (node == null ) {
this .root = new Node(data);
return this .root;
}
if (data <= node.data) {
node.left = this .insertRec(node.left, data);
}
else {
node.right = this .insertRec(node.right, data);
}
return node;
}
function Greater_BST(root)
{
var sum = 0;
var node = root;
var stack = [];
while (stack.length!= 0 || node != null ) {
while (node != null ) {
stack.push(node);
node = node.right;
}
node = stack.pop();
sum += node.data;
node.data = sum;
node = node.left;
}
}
insert(8);
insert(5);
insert(2);
insert(7);
insert(12);
insert(9);
insert(15);
Greater_BST(root);
inorder();
</script>
|
Output58 56 51 44 36 27 15
Time Complexity: O(n) , n is no.of Node in a BST.
Auxiliary Space: O(n). Stack is used for storing data.