- 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
80struct node{
int data;
int height;
node* lchild;
node* rchild;
};
node* newNode(int val){
node* root = new node;
root->data = val;
root->height = 1;
root->lchild = NULL;
root->rchild = NULL;
return root;
}
int getHeight(node* root){
if (root == 0){
return 0;
}
return root->height;
}
int getBalance(node* root){
return getHeight(root->lchild) - getHeight(root->rchild);
}
void updataHeight(node* root){
root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
void L(node* &root){
node* temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updataHeight(root);
updataHeight(temp);
temp = root;
}
void R(node* &root){
node* temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updataHeight(root);
updataHeight(temp);
temp = root;
}
void insert(node* &root, int x){
if (root == NULL){
root = newNode(x);
return;
}
if (x < root->data){
insert(root->lchild, x);
updataHeight(root);
if(getBalance(root) == 2){
if(getBalance(root->lchild) == 1){
R(root);
}
else if(getBalance(root->lchild) == -1){
L(root->lchild);
R(root);
}
}
}
else{
insert(root->rchild, x);
updataHeight(root);
if(getBalance(root) == -2){
if(getBalance(root->rchild) == -1){
L(root);
}
else if(getBalance(root->rchild) == 1){
R(root->rchild);
L(root);
}
}
}
}