AVL树的插入与旋转

定义

AVL树本质上是一颗二叉查找树,但是它又具有以下特点:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

插入与旋转

单旋

LL型

在根结点的左子树的左子树上插入节点。

RR型

在根结点的右子树的右子树上插入节点。

解决方法

双旋

LR型

在根结点的左子树的右子树上插入节点。

RL型

在根结点的右子树的左子树上插入节点。

解决方法

模板

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
#include <stdio.h>
#include <vector>
#include <string.h>
#include <queue>
#include <map>
#include <iostream>
#include <algorithm>
#include <string>
#include <math.h>
#include <stdlib.h>
using namespace std;
struct node
{
    int val;
    int high;
    node *left,*right;
    node(int x)
    {
        val=x;high=0;
        left=right=NULL;
    }
};
int gethigh(node *temp)
{
    if(temp==NULL)return -1;
    return temp->high;
}
node* SingleRotateLL(node *root)
{
    node *temp;
    temp=root->left;
    root->left=temp->right;
    temp->right=root;
    root->high=max(gethigh(root->left),gethigh(root->right))+1;     //更新高度
    temp->high=max(gethigh(temp->left),gethigh(temp->right))+1;     
    return temp;
}
node *SingleRotateRR(node *root)
{
    node *temp;
    temp=root->right;
    root->right=temp->left;
    temp->left=root;
    root->high=max(gethigh(root->left),gethigh(root->right))+1; //更新高度
    temp->high=max(gethigh(temp->left),gethigh(temp->right))+1;
    return temp;
}
node *DoubleRotateLR(node *root)
{
    root->left=SingleRotateRR(root->left);
    return SingleRotateLL(root);
}
node *DoubleRotateRL(node *root)
{
    root->right=SingleRotateLL(root->right);
    return SingleRotateRR(root);
}
node* Insert(node *root,int x)
{
    if(root==NULL){return new node(x);}
    if(x<root->val)
    {
        root->left=Insert(root->left,x);
        if(abs(gethigh(root->left)-gethigh(root->right))>1)
        {
            if(x<root->left->val)
                root=SingleRotateLL(root);
            else
                root=DoubleRotateLR(root);
        }
    }
    else
    {
        root->right=Insert(root->right,x);
        if (abs(gethigh(root->left)-gethigh(root->right))>1)
        {
            if(x>root->right->val)
                root=SingleRotateRR(root);
            else
                root=DoubleRotateRL(root);
        }
    }
    root->high=max(gethigh(root->left),gethigh(root->right))+1; //更新高度
    return root;
}
int main()
{
    int n,x;
    scanf("%d",&n);
    node *root=NULL;
    while(n--)
    {
        scanf("%d",&x);
        root=Insert(root,x);
    }
    printf("%d\n",root->val);
    return 0;
}
发布了9 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/yanpeng0823/article/details/88781676