04-树5 Root of AVL Tree 分数 25

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.

F1.jpg

F2.jpg

F3.jpg

F4.jpg

Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the root of the resulting AVL tree in one line.

#include <bits/stdc++.h>
using namespace std;
int n;
struct node{
	int x,h,p;
	node *l,*r;
};
int update(node *t){
	if(t == NULL)return 0;
	t->h = max(update(t->l ),update(t->r )) + 1;
	return t->h ;
}
node* insert(node *t,int a){
	if(t == NULL){
		t = new node;
		t->x = a;
		t->l = t->r  = NULL;
		t->h = 1;
		t->p = 0;
		return t;
	}else {
		if(a < t->x ){
			t->l = insert(t->l ,a);
			t->h = update(t);
			t->p = update(t->l ) - update(t->r ) ;//计算平衡因子 
			if(t->p == 2){
				if(t->l->p == 1){		//LL旋转 
					node *br,*b;
					b = t->l ;
					br = b->r ;
					t->l = br;
					b->r = t;
					update(b);
					return b;
				}else if(t->l->p == -1){//LR旋转 
					node *b,*c,*cl,*cr;
					b = t->l ;
					c = b->r ;
					cl = c->l ;
					cr = c->r ;
					b->r = cl;
					t->l = cr;
					c->l = b;
					c->r = t;
					update(c);
					return c;
				}
			}
			return t;
		}else if(a > t->x ){
			t->r = insert(t->r ,a);
			t->h = update(t);
			t->p = update(t->l ) - update(t->r ) ;
			if(t->p == -2){
				if(t->r->p == -1){		//RR旋转 
					node *b,*bl;
					b = t->r ;
					bl = b->l ;
					t->r = bl;
					b->l = t;
					update(b);
					return b;
				}else if(t->r->p == 1){	//RL旋转 
					node *b,*c,*cl,*cr;
					b = t->r ;
					c=  b->l ;
					cl = c->l ;
					cr = c->r ;
					t->r = cl;
					b->l = cr;
					c->l = t;
					c->r = b;
					update(c);
					return c;
				}
			}
			return t;
		}
	}
}
int main()
{
	cin>>n;
	node *t = NULL;
	for(int i = 1;i<=n;i++){
		int a;
		cin>>a;
		t = insert(t,a);
	}
	cout<<t->x ;
	return 0;
}

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值