-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAVL Insertion.cpp
More file actions
100 lines (98 loc) · 2.46 KB
/
AVL Insertion.cpp
File metadata and controls
100 lines (98 loc) · 2.46 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
typedef struct node
{
int val;
struct node* left;
struct node* right;
int ht;
} node;
int height(node *N)
{
if (N == NULL)
return -1;
return N->ht;
}
int getBalance(node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
void RotateLeft(node* root)
{
node* temp=root->left;
root->left=temp->right;
temp->right=root;
root->ht=(height(root->left)> height(root->right) ? height(root->left) : height(root->right))+1;
temp->ht=((height(temp->left) > height(temp->right)) ? height(temp->left) : height(temp->right))+1;
root=temp;
}
void RotateRight(node* root)
{
node* temp=root->right;
root->right=temp->left;
temp->left=root;
root->ht=((height(root->left ) > height(root->right)) ? height(root->left) : height(root->right))+1;
temp->ht=((height(temp->left) > height(temp->right)) ? height(temp->left) : height(temp->right))+1;
root=temp;
}
node * insert(node * root,int val)
{
if(root==NULL)
{
node *temp = (node*)malloc(sizeof(node));
temp->left=temp->right=NULL;
temp->ht=0;
temp->val=val;
return temp;
}
if(root->val<val){
root->right=insert(root->right,val);
// cout<<root->left->val<<endl;
//cout<<"In the insertion right "<<val<<endl;
}
else{
root->left=insert(root->left,val);
//cout<<"In the insertion left "<<val<<endl;
}
root->ht=((height(root->left) > height(root->right)) ? height(root->left) : height(root->right))+1;
int balanceFactor = getBalance(root);
cout<<"BALANCE FACTOR : "<<balanceFactor<<" "<<root->val<<endl;
if(balanceFactor>1)
{
if(height(root->left->left) > height(root->left->right))
RotateLeft(root);
else
{
RotateLeft(root->left);
RotateRight(root);
}
}
if(balanceFactor<-1)
{
if(height(root->right->right) < height(root->right->left))
RotateRight(root);
else
{
RotateRight(root->right);
RotateLeft(root);
}
}
return root;
}
int main()
{
node* root=NULL;
int a[]={3,2,4,5,6};
for(int i=0;i<5;i++){
root = insert(root,a[i]);
}
cout<<getBalance(root)<<" "<<root->val<<endl;
// cout<<getBalance(root->left)<<root->left->val<<endl;
cout<<getBalance(root->right)<<root->right->val<<endl;
cout<<getBalance(root->right->right)<<root->right->right->val<<endl;
return 0;
}