【浙大数据结构学习笔记】4.2 平衡二叉树

平衡二叉树

平衡因子: BF=hL - hR ,即左右树高的差。
定义: 空树,或者平衡因子 | BF(T) |<=1

#define ElementType int;
typedef struct AVLNode *Position;
typedef Position AVLTree;
struct AVLNode{
	ElementType Data;
	AVLTree Left,Right;
	int Height;
};

平衡二叉树的调整

左单旋

//左单旋 
AVLTree SingleLeftRotation(AVLTree A){
	//A必须有一个右结点B,A和B做左单旋,更新AB的树高,返回B 
	AVLTree B=A->Left;
	B->Right=A;
	A->Height=Max(GetTreeHeight(A->Left),GetTreeHeight(A->Right))+1;
	B->Height=Max(GetTreeHeight(B->Left),GetTreeHeight(B->Right))+1;
	return B;//平衡树的根结点更新成 B 
}

右单旋

//右单旋 
AVLTree SingleRightRotation(AVLTree A){
	//A必须有一个左结点B,A和B做右单旋,更新AB的树高,返回B 
	AVLTree B=A->Right;
	B->Left=A;
	A->Height=Max(GetTreeHeight(A->Left),GetTreeHeight(A->Right))+1;
	B->Height=Max(GetTreeHeight(B->Left),GetTreeHeight(B->Right))+1;
	return B;//平衡树的根结点更新成 B 
}

左右双旋

//左右双旋 
AVLTree SingleLeftRightRotation(AVLTree A){
	/*	A必须有一个左子结点B,B必须有一个右子结点C
		A和B做右单旋,A和C做左单旋 
	*/ 
	A->Left=SingleRightRotation(A->Left);
	return SingleLeftRotation(A);
}

右左双旋

//右左双旋 
AVLTree SingleRightLeftRotation(AVLTree A){
	/*	A必须有一个右子结点B,B必须有一个左子结点C
		A和B做左单旋,A和C做右单旋 
	*/ 
	A->Right=SingleLeftRotation(A->Right);
	return SingleRightRotation(A);
}

插入

//向平衡树中插入新的元素,并且返回调整后的平衡树 
AVLTree Insert(AVLTree T,ElementType X){
	if(!T){//原树空,插入新结点 
		T=(AVLTree)malloc(sizeof(struct AVLNode));
		T->Data=X;
		T->Left=T->Right=NULL;
		T->Height=0;
	}else if(X<T->Data){
		//向T的左子树插入X 
		T->Left=Insert(T->Left,X);
		//需要左旋 
		if(GetTreeHeight(T->Left)-GetTreeHeight(T->Left)==2)
			if(X<T->Left->Data)
				T=SingleLeftRotation(T);//左单旋 
			else
				T=SingleLeftRightRotation(T);//左右双旋 
	}else if(X>T->Data){
		//向T的右子树插入X 
		T->Right=Insert(T->Right,X);
		//需要右旋 
		if(GetTreeHeight(T->Left)-GetTreeHeight(T->Left)==-2)
			if(X>T->Right->Data)
				T=SingleRightRotation(T);//右单旋 
			else
				T=SingleLeftRightLeftRotation(T);//右左双旋 
	}/*else if(X==T->Data),无需插入*/
	//更新树高 
	T->Height=Max(GetTreeHeight(T->Left),GetTreeHeight(T->Right)) +1;
	
	return T;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值