#include<iostream>
#include<stdlib.h>
using namespace std;
struct AVLNode{ //创建平衡二叉树
int Data;
struct AVLNode* left;
struct AVLNode* right;
int height;
};
typedef struct AVLNode* AVLTree;
int GetHeight(AVLTree A)//获取该树的高度
{
if(!A) return 0;
return A->height;
}
AVLTree Left(AVLTree A)//进行左旋
{
AVLTree B=A->left;
A->left=B->right;
B->right=A;
A->height=max(GetHeight(A->left),GetHeight(A->right))+1;
B->height=max(GetHeight(B->left),A->height )+1;
return B;
}
AVLTree Right(AVLTree A)//右旋
{
AVLTree B=A->right;
A->right=B->left;
B->left=A;
A->height=max(GetHeight(A->left ),GetHeight(A->right ))+1;
B->height=max(GetHeight(B->right ),A->height )+1;
return B;
}
AVLTree Left_Right(AVLTree A)//左旋右旋
{
A->left=Right(A->left);
return Left(A);
}
AVLTree Right_Left(AVLTree A)//右旋左旋
{
A->right=Left(A->right );
return Right(A);
}
AVLTree Insert(AVLTree A,int Key)//向平衡二叉树中插入节点
{
if(!A)//若二叉树为空则开辟空间存储Key值
{
A=(struct AVLNode*)malloc(sizeof(struct AVLNode));
A->Data=Key;
A->height =0;
A->left =NULL;
A->right =NULL;
}
else if(Key<A->Data)//若Key小于A->Data则向A节点的左子树搜索
{
A->left=Insert(A->left,Key);
if(GetHeight(A->left)-GetHeight(A->right )==2)
{
if(Key<A->left->Data)
Left(A);
else Left_Right(A);
}
}
else if(Key>A->Data )
{
A->right =Insert(A->right ,Key);
if(GetHeight(A->left )-GetHeight(A->right )==-2)
{
if(Key>A->right->Data) Right(A);
else Right_Left(A);
}
}
A->height =max(GetHeight(A->left ),GetHeight(A->right ))+1;
return A;
}
int main()
{
int n;cin>>n;
AVLTree T=NULL;
for(int i=0;i<n;i++)
{
int Key;cin>>Key;
T=Insert(T,Key);
}
cout<<T->Data ;
}
pta平衡二叉树的根
于 2024-02-19 16:16:45 首次发布