-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConvert a BST to a Binary Tree such that sum of all greater keys is added to every key
95 lines (81 loc) · 1.99 KB
/
Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// C++ Program to change a BST to Binary Tree
// such that key of a node becomes original
// key plus sum of all greater keys in BST
#include <bits/stdc++.h>
using namespace std;
/* A BST node has key, left child
and right child */
struct node
{
int key;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node
with the given key and NULL left and right pointers.*/
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);
}
// A recursive function that traverses the
// given BST in reverse inorder and for
// every key, adds all greater keys to it
void addGreaterUtil(struct node *root, int *sum_ptr)
{
// Base Case
if (root == NULL)
return;
// Recur for right subtree first so that sum
// of all greater nodes is stored at sum_ptr
addGreaterUtil(root->right, sum_ptr);
// Update the value at sum_ptr
*sum_ptr = *sum_ptr + root->key;
// Update key of this node
root->key = *sum_ptr;
// Recur for left subtree so that the
// updated sum is added to smaller nodes
addGreaterUtil(root->left, sum_ptr);
}
// A wrapper over addGreaterUtil(). It initializes
// sum and calls addGreaterUtil() to recursively
// update and use value of sum
void addGreater(struct node *root)
{
int sum = 0;
addGreaterUtil(root, &sum);
}
// A utility function to print inorder
// traversal of Binary Tree
void printInorder(struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
cout << node->key << " " ;
printInorder(node->right);
}
// Driver Code
int main()
{
/* Create following BST
5
/ \
2 13 */
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;
}
// This code is contributed by SHUBHAMSINGH10