PAT A1066 Root of AVL Tree(***创建二叉平衡树)

问题链接: https://pintia.cn/problem-sets/994805342720868352/problems/994805404939173888

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
	int v, h;//v为结点权值,h为当前子树高度 
	node *lchild, *rchild;
};

//生成一个新结点 
node *newNode(int x){
	node *Node = new node;
	Node -> v = x;//结点权值 
	Node -> h = 1;//结点高度 
	Node -> lchild = NULL;
	Node -> rchild = NULL;
	return Node;
}

//获取以root为根结点的子树的当前高度
int height(node *root){
	if(root == NULL)
	    return 0;
	else
	    return root->h;
} 
//计算结点root的平衡因子 
int Balance(node *root){
	return height(root->lchild) - height(root->rchild);
}
//更新结点root的高度
void upheight(node *root){
	root->h = max(height(root->lchild), height(root->rchild)) + 1; 
} 
//左旋(Left Rotation) 
void Left(node *&root){
	node *temp = root->rchild;
	root->rchild = temp->lchild;
	temp->lchild = root;
	//更新高度 
	upheight(root); 
	upheight(temp); 
	
	root = temp;
} 
//右旋(Right Rotation) 
void Right(node *&root){
	node *temp = root->lchild;
	root->lchild = temp->rchild;
	temp->rchild = root;
	//更新高度
	upheight(root);
	upheight(temp);
	
	root = temp;
}

//插入权值为x的结点
void insert(node *&root, int x){
	if(root == NULL){
		root = newNode(x);
		return;
	}
	if(x < root->v){
		insert(root->lchild, x);
		upheight(root);
		if(Balance(root) == 2){//左右子树高度差2,则需要旋转 
			if(Balance(root->lchild) == 1)//LL型 
			    Right(root);
			else if(Balance(root->lchild) == -1) //LR型
			{
				Left(root->lchild);
				Right(root);
			} 
		}
	}else{
		insert(root->rchild, x);
		upheight(root);
		if(Balance(root) == -2){
			if(Balance(root->rchild) == -1)//RR型
			    Left(root);
			else if(Balance(root->rchild) == 1)//RL型
			{
				Right(root->rchild);
				Left(root);
			}		 
		}
	}
}


int main(){
	int n, x;
	cin >> n;
	
	node *root = NULL;
	for(int i = 0; i < n; i++){
		cin >> x;
		insert(root, x);
	}
		
	cout << root->v;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值