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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章