A1066 Root of AVL Tree (25分)

#include<cstdio>
#include<stdlib.h>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
using namespace std;
//A1066
const int maxn=20;
struct node{
	int data;
	int height;
	node *left;
	node *right;
};
int data[maxn];

node* newNode(int data){
	node *root=new node;
	root->data=data;
	root->left=root->right=NULL;
	root->height=1;
	return root;
}
int getHeight(node* root){
	if(root==NULL)return 0;
	else return root->height;
}
int getAVLFactor(node* root){//一定要使用getHeight,万一节点是null直接用指针获取不到节点的高
	int result=getHeight(root->left)-getHeight(root->right);
//	cout<<"factor="<<result<<endl;
	return result;
}
void updateHeight(node* root){
	root->height= max(getHeight(root->left),getHeight(root->right))+1;
}
void R(node* &root){
	node* temp=root->left;
	root->left=temp->right;
	temp->right=root;
	//从下到上更新节点的高度 
	updateHeight(root);
	updateHeight(temp);
	root=temp;
}
void L(node* &root){
	node* temp=root->right; 
	root->right=temp->left;
	temp->left=root;
	updateHeight(root);//如果返回int的话,直接调用里面就没有更新操作了
	updateHeight(temp);
	root=temp;	
}
void insert(node* &root,int data){
	if(root==NULL){
		root=newNode(data);
//		cout<<"root.data="<<data<<endl;
		return;
	}
	if(data<root->data){//应该插入左子树 
		insert(root->left,data);
		updateHeight(root);
//		cout<<"getAVLFactor(root)"<<getAVLFactor(root)<<endl;
		if(getAVLFactor(root)==2){
			if(getAVLFactor(root->left)==1){//LL
				R(root);
			}else if(getAVLFactor(root->left)==-1){//LR
				L(root->left);
				R(root);
			}
		}	
	}else{
		insert(root->right,data);
		updateHeight(root);
		
		if(getAVLFactor(root)==-2){
			if(getAVLFactor(root->right)==-1){//RR
				L(root);
			}else if(getAVLFactor(root->right)==1){//RL
				R(root->right);
				L(root);
			}
		}
	}
	
}


int main()
{
	int n;
	scanf("%d",&n);
	node *root=NULL;
	int data;
	
	for(int i=0;i<n;i++){
		scanf("%d",&data);
		insert(root,data);
	}
	printf("%d",root->data);
	
return 0;
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值