-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAVLTrees.cpp
More file actions
125 lines (115 loc) · 2.79 KB
/
Copy pathAVLTrees.cpp
File metadata and controls
125 lines (115 loc) · 2.79 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
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
#include <bits/stdc++.h>
using namespace std;
using lli = long long int;
using pii = pair<int,int>;
// AVL Trees
struct Node
{
int data;
Node *left,*right;
int height;
Node(int val)
{
data=val;
height=0;
left=right=NULL;
}
};
Node * rightRotate(Node *root)
{
Node *newRoot = root->left;
Node *temp=newRoot->right;
root->left=temp;
newRoot->right=root;
root->height=1+max(root->left->height,root->right->height);
newRoot->height=1+max(newRoot->left->height,newRoot->right->height);
return newRoot;
}
Node * leftRotate(Node *root)
{
Node *newRoot = root->right;
Node *temp=newRoot->left;
root->right=temp;
newRoot->left=root;
root->height=1+max(root->left->height,root->right->height);
newRoot->height=1+max(newRoot->left->height,newRoot->right->height);
return newRoot;
}
Node *insertVal(Node *root,int val)
{
if(root==NULL)
{
Node *temp=new Node(val);
return temp;
}
if(root->data<val)
{
root->right=insertVal(root->right,val);
}
else
{
root->left=insertVal(root->left,val);
}
int balance=0;
if(root->left!=NULL)
balance+=root->left->height;
if(root->right!=NULL)
balance-=root->right->height;
if(balance>1) // left subtree is heavier
{
// root->left exists
int leftWeight=root->left->left!=NULL? root->left->left->height : 0;
int rightWeight=root->left->right!=NULL? root->left->right->height : 0;
if(leftWeight>rightWeight) // LL type -> R rotation
root=rightRotate(root);
else // LR type -> First L rotation on root->left, then R rotation on root
{
root->left=leftRotate(root->left);
root=rightRotate(root);
}
}
else if(balance<-1) // right subtree is heavier
{
//root->right exists
int leftWeight=root->right->left!=NULL? root->right->left->height : 0;
int rightWeight=root->right->right!=NULL? root->right->right->height : 0;
if(rightWeight>leftWeight) // RR type -> L rotation
root=leftRotate(root);
else // RL type -> First R rotation on root->right, then L rotation on root
{
root->right=rightRotate(root->right);
root=leftRotate(root);
}
}
return root;
}
void inorder(Node *root)
{
if(root==NULL)
return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
return;
}
int main()
{
int n;
cin>>n;
vector<int> v;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
v.push_back(x);
}
Node *root = NULL;
for(int i=0;i<n;i++)
{
root = insertVal(root,v[i]);
inorder(root);
cout<<endl;
}
cout<<endl;
return 0;
}