pta平衡二叉树的根

#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 ;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SuperRandi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值