练习4.2 平衡二叉树的根 (浙大《数据结构》第2版)

传送门:https://pintia.cn/problem-sets/434/problems/6103

AC代码:

#include
#include
#include
#include
using namespace std;

struct AVLNode{
	int Data;       /*结点数据*/
	AVLNode * Left; /*指向左子树*/
	AVLNode * Right;/*指向右子树*/
	int Height;     /*树高*/
};

typedef struct AVLNode * Position;/*定义结构体指针别名为Position*/ 
typedef Position AVLTree;

int Max(int a, int b)
{
	return a > b ? a:b;
}

int GetHeight(AVLTree A)
{/*获取结点A的高度*/
	int L,R;
	
	if(A){
		L=GetHeight(A->Left);/*求左子树的高度*/
		R=GetHeight(A->Right);/*求右子树的高度*/
		return L>R ? (L+1):(R+1);
	}
	
	else return 0;/*空树高度为0*/
}

AVLTree SingleLeftRotation(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 SingleRightRotation(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 DoubleLeftRightRotation(AVLTree A)
{
	A->Left=SingleRightRotation(A->Left);
	return SingleLeftRotation(A);
}

AVLTree DoubleRightLeftRotation(AVLTree A)
{
	A->Right=SingleLeftRotation(A->Right);
	return SingleRightRotation(A);
}

AVLTree Insert(AVLTree T, int X)
{/*将X插入AVL树T中,并且返回调整后的AVL树*/ 
	if(!T){ /*若插入空树,则新建包含一个结点的树*/
		//T=(AVLTree)malloc(sizeof(struct AVLNode));
		T=new AVLNode;
		T->Data = X;
		T->Height = 1;
		T->Left = T->Right = NULL;	
	} /*if(插入空树)结束*/
	
	else if( X < T->Data ){
		/*插入T的左子树*/
		T->Left = Insert ( T->Left ,X);
		/*如果需要左旋*/
		if(GetHeight(T->Left)-GetHeight(T->Right)==2)
			if(XLeft->Data)
				T=SingleLeftRotation(T);    /*左单旋*/
			else
				T=DoubleLeftRightRotation(T);    /*左-右双旋*/
	} /*else if(插入左子树)结束*/
	
	else if (X>T->Data){
		/*插入T的右子树*/
		T->Right = Insert ( T->Right ,X);
		/*如果需要右旋*/
		if(GetHeight(T->Left)-GetHeight(T->Right)==-2)
			if(X>T->Right->Data)
				T=SingleRightRotation(T);    /*右单旋*/
			else
				T=DoubleRightLeftRotation(T);    /*右-左双旋*/
	} /*else if(插入右子树)结束*/
	
	/*else X==T->Data, 无需插入 */
	
	/*别忘了更新树高*/
	T->Height = Max(GetHeight(T->Left), GetHeight(T->Right))+1;
	
	return T;	
}

int main(){
	int n,x;
	AVLTree A=NULL;
	scanf("%d",&n);
	for(int i=0;iData);
	return 0;	
}

 

你可能感兴趣的:(练习4.2 平衡二叉树的根 (浙大《数据结构》第2版))