平衡二叉树实现 A1066 root of avl tree

AVL平衡二叉树 实现 查询时间复杂度 O(logn)
LL 左旋 root 2 root->lchild=1
LR 左旋后右旋 root 2 root->lchild=-1
RR 右旋 root=-2 root->rchild=-1
RL 右旋后左旋 root=-2 root->rchild=1

#include<cstdio>
#include<algorithm>
using namespace std;
struct node
{
	int data;
	node *right ,*left;
	int height;
};
node * newnode(int v)
{
	node * nd=new node;
	nd->data=v;
	nd->left=NULL;nd->right=NULL;
	nd->height=1;
}
int getheight(node * nd)
{
	if(nd==NULL)return 0;
	return nd->height;
}
int getbalancefactor(node *nd)
{
	//if(nd==NULL) return 0;
	//return nd->left->height-nd->right->height;
	return getheight(nd->left)-getheight(nd->right);
}
void updateheight(node *nd)
{
	//nd->height=max(nd->left->height,nd->right->height)+1;
	nd->height=max(getheight(nd->left),getheight(nd->right))+1;
}
void l(node * &root)//左旋
{
	node *temp=root->left;
	root->right=temp->left;
	temp->left=root;
	updateheight(root);
	updateheight(temp);
	root=temp;
}
void r(node * &root)//右旋
{
	node*temp=root->right;
	root->left=temp->right;
	temp->right=root;
	updateheight(root);
	updateheight(temp);
	root=temp;
}
void insert (node * &root ,int v)
{
	if(root==NULL)
	{
		newnode(v);
		return;
	}
	if(v<root->data)
	{
		insert(root->left,v);
		updateheight(root);
		if(getbalancefactor(root)==2)
		{
			if(getbalancefactor(root->left)==1)
			{
				r(root);
			}
			else 
			{
				r(root->left);
				l(root);
			}
		}
	}
	else
	{
		insert(root->right,v);
		updateheight(root);
		if(getbalancefactor(root)==-2)
		{
			if(getbalancefactor(root->right)==-1)
			{
				l(root);
			}
			else
			{
				l(root->right);
				r(root);
			}
		}
	}
}
const int maxn=21;
int main()
{
	int n,a;
	scanf("%d",&n);
	node *root=NULL;
	for(int i=0;i<n;i++)
	{
		scanf("%d",&a);
		insert(root,a);
	}
	printf("%d",root->data);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值