题意:构造一颗AVL树,输出其根节点
思路:构造AVL树即二叉平衡树,可以参考严奶奶的数据结构构造AVL树,过程差不多,只是没有用平衡因子,直接求出左右孩子的深度,简化了一些对平衡因子的修改,其余思想都差不多
代码:
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct node {
int data;
struct node *lchild, *rchild;
}*pNode;
void R_Rotate(pNode &T) {
pNode lc = T->lchild;
T->lchild = lc->rchild;
lc->rchild = T;
T = lc;
}
void L_Rotate(pNode &T) {
pNode rd = T->rchild;
T->rchild = rd->lchild;
rd->lchild = T;
T = rd;
}
void LeftBalence(pNode &T) {
L_Rotate(T->lchild);
R_Rotate(T);
}
void RightBalence(pNode &T) {
R_Rotate(T->rchild);
L_Rotate(T);
}
int getDepth(pNode T) {
if (T == NULL)return 0;
int l = getDepth(T->lchild);
int r = getDepth(T->rchild);
return max(l, r) + 1;
}
void InsertAVL(pNode &T,int value) {
if (T == NULL) {
T = new node();
T->data = value;
T->lchild = T->rchild = NULL;
return;
}
if (value < T->data) {
InsertAVL(T->lchild,value);
int l = getDepth(T->lchild),r = getDepth(T->rchild);
if (l - r >= 2) {//当发现第一个不平衡的点的时候开始调整
if(value<T->lchild->data){//插入到左子树的左子树发现不平衡时
R_Rotate(T);
}
else {
LeftBalence(T);
}
}
}
else {
InsertAVL(T->rchild, value);
int l = getDepth(T->lchild), r = getDepth(T->rchild);
if (r - l >= 2) {
if (value > T->rchild->data) {
L_Rotate(T);
}
else {
RightBalence(T);
}
}
}
}
int main() {
int n = 0,tem = 0;
pNode T = NULL;
cin >> n;
for (int i = 0; i < n; i++) {
scanf("%d",&tem);
InsertAVL(T,tem);
}
cout << T->data << endl;
system("pause");
return 0;
}