7-13 平衡二叉树的根 (25 分)

这道题是关于平衡树的例题,其中可以作为模板在我们学习的过程中,平衡树重点是调平衡,其中调平衡力又有RR类和LL类是最基本的,知道了这两个类也就能知道LR和RL是怎么的原理。不过最近我也总是遇到其他麻烦,总是在建树的时候遇到各种各样的麻烦。
#include<bits/stdc++.h>
using namespace std;
typedef struct AVLNode {
	int data;
	int height;
	struct AVLNode* lchild,* rchild;
}*AVLTree;
int height(AVLTree T) {
	if(!T)return 0;
	return T->height;
}
void updataHeight(AVLTree &T) {
	if(!T) return ;
	T->height = max(height(T->lchild),height(T->rchild))+1;
}
AVLTree LL_Rotation(AVLTree &T) {
	AVLTree temp = T->lchild;
	T->lchild = temp->rchild;
	temp->rchild = T;
	updataHeight(T);
	updataHeight(temp);
	return temp;
}
AVLTree RR_Rotation(AVLTree &T) {
	AVLTree temp = T->rchild;
	T->rchild = temp->lchild;
	temp->lchild = T;
	updataHeight(T);
	updataHeight(temp);
	return temp;
}
AVLTree RL_Rotation(AVLTree &T) {
	T->rchild = LL_Rotation(T->rchild);
	return RR_Rotation(T);
}
AVLTree LR_Rotation(AVLTree &T) {
	T->lchild = RR_Rotation(T->lchild);
	return  LL_Rotation(T);
}
void adjust(AVLTree &T) {
	if(!T) return ;
	if(height(T->lchild)-height(T->rchild)>1) {
		if(height(T->lchild->lchild)>=height(T->lchild->rchild)) {
			T = LL_Rotation(T);
		} else {
			T = LR_Rotation(T);
		}
	} else if(height(T->rchild)-height(T->lchild)>1) {
		if(height(T->rchild->rchild)>=height(T->rchild->lchild)) {
			T = RR_Rotation(T);
		} else {
			T = RL_Rotation(T);
		}
	}
}
AVLTree insert(AVLTree &T,int x) {
	if(!T) {
		T = new AVLNode;
		T->height = 1;
		T->lchild = T->rchild = NULL;
		T->data = x;
		return T;
	}
	if(T->data==x) return T;
	if(T->data>x) {
		T->lchild = insert(T->lchild,x);
	} else {
		T->rchild = insert(T->rchild,x);
	}
	updataHeight(T);
	adjust(T);
	return T;
}
AVLTree delete1(AVLTree &T,int x) {
	if(!T)return NULL;
	if(T->data==x) {
		if(!T->lchild||!T->rchild) {
			AVLTree temp = T;
			T = T->lchild ? T->lchild : T->rchild;
			delete temp;
		} else { //用直接前驱代替这个点,然后再删除他。
			AVLTree temp = T->lchild;
			while(temp->rchild) {
				temp = temp->rchild;
			}
			T->data = temp->data;
			delete1(T->lchild,T->data);
		}
	} else if(T->data>x) {
		T->lchild = delete1(T->lchild,x);
	} else if(T->data<x) {
		T->rchild = delete1(T->rchild,x);
	}
	updataHeight(T);
	adjust(T);
	return T;
}
void preOrder(AVLTree T){
	if(T){
		cout<<T->data<<"\t"<<T->height<<endl;
		preOrder(T->lchild);
		preOrder(T->rchild);
	}
}
int main() {
	int n;
	int a;
	cin>>n;
	AVLTree T = NULL;
	for(int i = 0; i < n; i++) {
		cin>>a;
		T = insert(T,a);
	}
//	preOrder(T);
	cout<<T->data<<endl;
	return 0;
}

  

posted @ 2022-04-22 19:36  没停过WA  阅读(35)  评论(0编辑  收藏  举报