1066. Root of AVL Tree (25)

#include <iostream>
#include <cstdio>
using namespace std;

struct node {
	int key;
	node *left, *right;
	int h;
};

inline void update(node *t) {
	int lh = t->left ? t->left->h : 0;
	int rh = t->right ? t->right->h : 0;
	t->h = (lh > rh ? lh : rh) + 1;
}

void insert(node * &t, int d) {
	if(t) {
		insert(d > t->key ? t->right : t->left, d);
		int lh = t->left ? t->left->h : 0;
		int rh = t->right ? t->right->h : 0;

		if(lh - rh > 1) {
			int llh = t->left->left ? t->left->left->h : 0;
			int lrh = t->left->right ? t->left->right->h : 0;
			if(llh > lrh) {
				node *nt = t->left;
				t->left = nt->right;
				nt->right = t;
				t = nt;

				update(t->right);
			}
			else {
				node *nt = t->left->right;
				node *tl = t->left;
				tl->right = nt->left;
				t->left = nt->right;
				nt->left = tl;
				nt->right = t;
				t = nt;

				update(t->left);
				update(t->right);
			}
		}
		else if(lh - rh < -1) {
			int rlh = t->right->left ? t->right->left->h : 0;
			int rrh = t->right->right ? t->right->right->h : 0;
			if(rrh > rlh) {
				node *nt = t->right;
				t->right = nt->left;
				nt->left = t;
				t = nt;

				update(t->left);
			}
			else {
				node *nt = t->right->left;
				node *tr = t->right;
				tr->left = nt->right;
				t->right = nt->left;
				nt->right = tr;
				nt->left = t;
				t = nt;

				update(t->left);
				update(t->right);
			}
		}

		update(t);
	}
	else {
		t = new node;
		t->key = d;
		t->left = t->right = 0;
		t->h = 1;
	}
}

int main(int argc, char **argv) {
	int n;
	cin >> n;

	node *t = 0;
	for(int i = 0; i < n; i ++) {
		int d;
		scanf("%d", &d);
		insert(t, d);
	}
	printf("%d\n", t->key);

	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值