7-4 Root of AVL Tree (20分)

在这里插入图片描述

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the root of the resulting AVL tree in one line.

Sample Input 1:

5
88 70 61 96 120

Sample Output 1:

70

Sample Input 2:

7
88 70 61 96 120 90 65

Sample Output 2:

88

思路:

就是最基本的AVL插入操作。注意分清楚四种旋转,以及单旋和双旋之间的关系。

源码:

#include<stdio.h>
#include<stdlib.h>
typedef struct AVLNode *AVLTree;
typedef int ElementType;
struct AVLNode{
	ElementType Data;
	AVLTree Left;
	AVLTree Right;
	int height;
};
int GetHeight(AVLTree T)
{
	//求树高
	if(!T)return 0;
	return T->height;
}
AVLTree SingleRight(AVLTree T)
{
	//右单旋
	AVLTree oracle=T->Right;
	T->Right=oracle->Left;
	oracle->Left=T;
	int l,r;
	l=GetHeight(T->Left);
	r=GetHeight(T->Right);
	T->height=(l>r?l:r)+1;
	int Or;
	Or=GetHeight(oracle->Right);
	oracle->height=(T->height>Or?T->height:Or)+1;
	return oracle;
}
AVLTree SingleLeft(AVLTree T)
{
	//左单旋
	AVLTree oracle=T->Left;
	T->Left=oracle->Right;
	oracle->Right=T;
	int l,r;
	l=GetHeight(T->Left);
	r=GetHeight(T->Right);
	T->height=(l>r?l:r)+1;
	int ol;
	ol=GetHeight(oracle->Left);
	oracle->height=(T->height>ol?T->height:ol)+1;
	return oracle;
}
AVLTree DoubleRightLeft(AVLTree T)
{
	//右左双旋本质就是 右子树一次左旋+当前树结点一次右旋
	T->Right=SingleLeft(T->Right);
	return SingleRight(T);
}
AVLTree DoubleLeftRight(AVLTree T)
{
	//左右双旋本质就是 左子树一次右旋+当前树结点一次左旋
	T->Left=SingleRight(T->Left);
	return SingleLeft(T);
}
AVLTree Insert(AVLTree T,ElementType data)
{
	if(!T)
	{
		//树空则先建树
		T=(AVLTree)malloc(sizeof(struct AVLNode));
		T->Data=data;
		T->Left=T->Right=NULL;
		T->height=0;
	}
	else if(data>T->Data)
	{
		T->Right=Insert(T->Right,data);
		if(GetHeight(T->Right)-GetHeight(T->Left)==2)
		{
			/*如果发现BF遭到破坏*/ 
			if(data>T->Right->Data)
			/*右单旋*/ 
			T=SingleRight(T);
			else
			/*右左双旋*/
			T=DoubleRightLeft(T);
		}
	}
	else
	{
		T->Left=Insert(T->Left,data);
		if(GetHeight(T->Right)-GetHeight(T->Left)==-2)
		{
			if(data<T->Left->Data)
			/*左单旋*/
			 T=SingleLeft(T);
			else
			/*右左双旋*/
			T=DoubleLeftRight(T); 
		}
	}
	//注意更新树高
	int l,r;
	l=GetHeight(T->Left);
	r=GetHeight(T->Right);
	T->height=(l>r?l:r)+1;
	return T;
}
int main()
{
	int N;
	scanf("%d",&N);
	int i;
	ElementType data;
	AVLTree T=NULL;
	for(i=0;i<N;i++)
	{
		scanf("%d",&data);
		T=Insert(T,data);
	}
	printf("%d",T->Data);
	
	return 0;
} 
发布了82 篇原创文章 · 获赞 12 · 访问量 1848
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 黑客帝国 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览