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

 完全考察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;
}

 

    原文作者:AVL树
    原文地址: https://blog.csdn.net/w419387229/article/details/82379323
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞