-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Binary tree to BST.cpp
62 lines (53 loc) · 1.07 KB
/
Binary tree to BST.cpp
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
#include <bits/stdc++.h>
#include<set>
using namespace std;
class node {
public:
int data;
node *left, *right;
}*root;
node* GetNode(int d) {
node *nn=new(node);
nn->left = NULL;
nn->right = NULL;
nn->data = d;
return nn;
}
void InOrder(node *root) {
if(root == NULL)
return ;
InOrder(root->left);
cout<<root->data<<" ";
InOrder(root->right);
}
void StoreData(node *root,set<int> &s){ //&s reference of original set
if(root == NULL)
return ;
StoreData(root->left,s);
s.insert(root->data);
StoreData(root->right,s);
}
void ConvertToBST(node *root, auto &it) {
if(root == NULL)
return ;
ConvertToBST(root->left, it);
root->data = *it;
it++;
ConvertToBST(root->right, it);
}
int main()
{
root = GetNode(8);
root->left = GetNode(3);
root->right = GetNode(5);
root->left->left = GetNode(10);
root->left->right = GetNode(2);
root->right->left = GetNode(4);
root->right->right = GetNode(6);
InOrder(root);
set<int> s;
StoreData(root,s);
auto it = s.begin();
ConvertToBST(root,it);
InOrder(root);
}