PAT (Advanced Level) 1066 Root of AVL Tree (AVL树构造)

本文详细介绍了AVL树的数据结构实现及其插入操作后的平衡调整过程。通过具体的C++代码实现,展示了如何进行左旋、右旋及双旋转等操作来保持AVL树的平衡性质。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 完全考察AVL树的建树,光看书感觉已经掌握了,结果敲的时候发现总会漏一些细节

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct AVLNode * Position;
typedef Position AVLTree;
typedef struct AVLNode{
	int Data;
	AVLTree Left;
	AVLTree Right;
	int Height;
};

int n;
int GetHeight(AVLTree t){
	if(t)
		return t->Height;
	else
		return 0;
}

AVLTree SingleLeftRotate(AVLTree a){
	AVLTree tmp = a->Left;
	a->Left = tmp->Right;//先把原左子树的右子树接到a
	tmp->Right = a;
	a->Height = max(GetHeight(a->Left), GetHeight(a->Right)) + 1;
	tmp->Height = max(GetHeight(tmp->Left), GetHeight(tmp->Right)) + 1;
	return tmp;
}

AVLTree SingleRightRotate(AVLTree a){
	AVLTree tmp = a->Right;
	a->Right = tmp->Left;
	tmp->Left = a;
	a->Height = max(GetHeight(a->Left), GetHeight(a->Right)) + 1;
	tmp->Height = max(GetHeight(tmp->Left), GetHeight(tmp->Right)) + 1;
	return tmp;
}

AVLTree DoubleLeftRightRotate(AVLTree a){
	a->Left = SingleRightRotate(a->Left);
	return SingleLeftRotate(a);
}

AVLTree DoubleRightLeftRotate(AVLTree a){
	a->Right = SingleLeftRotate(a->Right);
	return SingleRightRotate(a);
}

AVLTree InsertToTree(AVLTree t, int x){
	if(!t){
		t = (AVLTree)malloc(sizeof(struct AVLNode));
		t->Data = x;
		t->Height = 1;
		t->Left = t->Right = NULL;
	}
	else if(x < t->Data){
		t->Left = InsertToTree(t->Left,x);
		if(GetHeight(t->Left) - GetHeight(t->Right) == 2)
			if(x < t->Left->Data)//LL型
				t = SingleLeftRotate(t);
			else//LR型
				t = DoubleLeftRightRotate(t);
	}
	else if(x > t->Data){
		t->Right = InsertToTree(t->Right,x);
		if(GetHeight(t->Right) - GetHeight(t->Left) == 2)
			if(x > t->Right->Data)//RR型
				t = SingleRightRotate(t);
			else//RL型
				t = DoubleRightLeftRotate(t);
	}
	t->Height = max(GetHeight(t->Left), GetHeight(t->Right)) + 1;
	return t;
}
int main(){
	scanf("%d",&n);
	int d;
	AVLTree tree = NULL;
	for(int i = 0; i < n; ++i){
		scanf("%d",&d);
		tree = InsertToTree(tree,d);
	}
	printf("%d",tree->Data);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值