-
Notifications
You must be signed in to change notification settings - Fork 0
/
AVL Tree
115 lines (88 loc) · 2.14 KB
/
AVL Tree
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
#include<bits/stdc++.h>
using namespace std;
struct Node
{
struct Node *lchild;
int data;
int height ;// we need to store the height 0f each node
struct Node *rchild;
}*root=NULL;
int NodeHeight(struct Node *p)
{ int hl,hr;
hl= p&&p->lchild?p->lchild->height:0;
hr= p&&p->rchild?p->rchild->height:0;
return max(hl+1,hr+1);
}
int BalanceFactor(struct Node *p)
{ int hl,hr;
hl= p&&p->lchild?p->lchild->height:0;
hr= p&&p->rchild?p->rchild->height:0;
return max(hl-hr);
}
struct Node * LLRotation(struct Node *p)
{
struct Node *p1=p->lchild;
struct Node *plr=pl->rchild;
pl->rchild=p;
p->lchild=plr;
p>height=NodeHeight(p);
pl->height=NodeHeight(pl);
if(root==p)
root=pl;
return pl;
}
struct Node * RRRotation(struct Node *p)
{
struct Node *p1=p->rchild;
struct Node *plr=pl->lchild;
pl->lchild=p;
p->rchild=plr;
p>height=NodeHeight(p);
pl->height=NodeHeight(pl);
if(root==p)
root=pl;
return pl;
}
struct Node * LRRotation(struct Node *p)
{
struct Node *pl=p->lchild;
struct Node *plr=pl->rchild;
pl->rchild=plr->lchild;
p->lchild=plr->rchild;
plr->lchild=pl;
plr->rchild=p;
pl->height=NodeHeight(pl);
p->height=NodeHeight(p);
plr->height=NodeHeight(plr);
if(root==p)
root=plr;
return plr;
}
struct Node *Insert(struct Node *p,int key)
{
struct Node *t;
if(p==NULL)
{
t=(struct Node *)malloc(sizeof(struct Node));
t->data=key;
t->height=1;
t->lchild=t->rchild=NULL;
return t;
}
if(p->data>key)
{
p->lchild=Insert(p->lchild,key);
}
else if(p->data<key)
p->rchild=Insert(p->rchild,key);
p->height=NodeHeigth(p);
if(BalanceFactor(p)==2&&BalanceFactor(p->lchild)==1) //LLROTATION
return LLRotation(p);
else if(BalanceFactor(p)==2&&BalanceFactor(p->lchild)==-1)
return LRRotation(p);
else if(BalanceFactor(p)==-2&&BalanceFactor(p->lchild)==-1)
return RRRotation(p);
else if(BalanceFactor(p)==-2&&BalanceFactor(p->lchild)==1)
return RLRotaion(p);
return p;
}