forked from intrinsi/coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTransformaBSTtogreatersumtree.cpp
More file actions
82 lines (67 loc) · 1.7 KB
/
TransformaBSTtogreatersumtree.cpp
File metadata and controls
82 lines (67 loc) · 1.7 KB
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
// C++ program to transform a BST to sum tree
#include<iostream>
using namespace std;
// A BST node
struct Node
{
int data;
struct Node *left, *right;
};
// A utility function to create a new Binary Tree Node
struct Node *newNode(int item)
{
struct Node *temp = new Node;
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
// Recursive function to transform a BST to sum tree.
// This function traverses the tree in reverse inorder so
// that we have visited all greater key nodes of the currently
// visited node
void transformTreeUtil(struct Node *root, int *sum)
{
// Base case
if (root == NULL) return;
// Recur for right subtree
transformTreeUtil(root->right, sum);
// Update sum
*sum = *sum + root->data;
// Store old sum in current node
root->data = *sum - root->data;
// Recur for left subtree
transformTreeUtil(root->left, sum);
}
// A wrapper over transformTreeUtil()
void transformTree(struct Node *root)
{
int sum = 0; // Initialize sum
transformTreeUtil(root, &sum);
}
// A utility function to print indorder traversal of a
// binary tree
void printInorder(struct Node *root)
{
if (root == NULL) return;
printInorder(root->left);
cout << root->data << " ";
printInorder(root->right);
}
// Driver Program to test above functions
int main()
{
struct Node *root = newNode(11);
root->left = newNode(2);
root->right = newNode(29);
root->left->left = newNode(1);
root->left->right = newNode(7);
root->right->left = newNode(15);
root->right->right = newNode(40);
root->right->right->left = newNode(35);
cout << "Inorder Traversal of given tree\n";
printInorder(root);
transformTree(root);
cout << "\n\nInorder Traversal of transformed tree\n";
printInorder(root);
return 0;
}