-
Notifications
You must be signed in to change notification settings - Fork 6
/
test.cpp
149 lines (136 loc) · 3.4 KB
/
test.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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include <iostream>
using namespace std;
struct node
{
int value;
node *left,*right;
};
int height(node *root) //used recursive operation to find heightof BST
{
if(root==NULL)
return 0;
int lh=0,rh=0;
lh=height(root->left);
rh=height(root->right);
if(lh>rh)
return (lh+1);
else
return(rh+1);
if(lh==rh)
return (rh+1);
}
void inorder(node *root) //used the defined inorder traversal
{
if (root != NULL)
{
inorder(root->left);
cout<<root->value<<" ";
inorder(root->right);
}
}
void preorder(node *root) //used the defined preorder traversal
{
if(root != NULL)
{
cout<<root->value<<" ";
preorder(root->left);
preorder(root->right);
}
}
node *leftrotate(node *root)
{
node *x,*y; //initialised x to root
x=root;
if(x->right!=NULL)
{
y=x->right; //y is x's right now i.e if x's right !=0
x->right=y->left;
y->left=x;
return y;
}
return x;
}
node *rightrotate(node *root)
{
node *k,*l; //initialised l to root
l=root;
if(l->left!=NULL) //k is l's left now i.e if l's left !=0
{
k=l->left;
l->left=k->right;
k->right=l;
return k;
}
return l;
}
node *insert( node *root,int key)
{
node*temp=new node;
temp->value=key;
temp->right=NULL;
temp->left=NULL;
if(root==NULL) //inserting values if root is NULL
{
root=temp;
}
else
if(key>root->value) //else checking value is greater or smaller than root's value
{
root->right=insert(root->right,key);
}
else
if(key<root->value)
{
root->left=insert(root->left,key);
}
return root;
}
node *makeskew(node *root)
{
node *p=root;
//while(p->right!=NULL) //continuing until root's right is not equal to 0
while(p->left!=NULL) //till root's left is not equal to 0
{
p=rightrotate(p); //rotating
}
p=p->right; //changing roots value
p=makeskew(p); //recursively continuing
return root;
}
int main()
{
node *root = NULL;
int h,i,n,val;
cout<<"enter no. ";
cin>>n;
for(i=0;i<n;i++)
{
cin>>val;
if(i==0)
{
root=insert(root,val);
}
else
insert(root,val);
}
cout<<"preorder : ";
preorder(root);
cout<<endl;
cout<<"inorder : ";
inorder(root);
cout<<endl;
h=height(root);
h=h-1;
cout<<h<<endl;
// cout<<root->value<<endl;
// root=leftrotate(root);
root=rightrotate(root);
// cout<<root->value<<endl;
// cout<<"preorder : ";
// preorder(root);
root=makeskew(root);
cout<<endl;
cout<<"preorder : ";
preorder(root);
return 0;
}