1066 Root of AVL Tree

25 篇文章 0 订阅
11 篇文章 0 订阅

主要要记得加引用,还有LR RL的旋转方法,是先旋转成LL或者RR,再R或L旋转

数据结构题好像没什么case恶心的....


#include <cstdio>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <cstring>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <ctype.h>
using namespace std;
struct BTnode {
	int v, height;
	BTnode *lchild, *rchild;
}*root;
int getHeight(BTnode* root) {
	if (root == NULL)	return 0;
	return root->height;
}
void updataHeight(BTnode* root) {
	root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
int getBalance(BTnode* root) {
	return getHeight(root->lchild) - getHeight(root->rchild);
}
void L(BTnode* &root) {
	BTnode* temp = root->rchild;
	root->rchild = temp->lchild;
	temp->lchild = root;
	updataHeight(root);
	updataHeight(temp);
	root = temp;
}
void R(BTnode* &root) {
	BTnode *temp = root->lchild;
	root->lchild = temp->rchild;
	temp->rchild = root;
	updataHeight(root);
	updataHeight(temp);
	root = temp;
}
void insert(BTnode* &root, int v) {
	if (root == NULL) {
		root = new BTnode;
		root->v = v;
		root->height = 1;
		root->lchild = root->rchild = NULL;
		return;
	}
	if (v < root->v) {
		insert(root->lchild, v);
		updataHeight(root);
		if (getBalance(root) == 2) {//左高
			if (getBalance(root->lchild) == 1) {//LL型
				//右旋
				R(root);
			}
			else if (getBalance(root->lchild) == -1) {
				//LR型 先L变成LL 再R
				L(root->lchild);
				R(root);
			}
		}
	}
	else {
		insert(root->rchild, v);
		updataHeight(root);
		if (getBalance(root) == -2) {//右高
			if (getBalance(root->rchild) == -1) {
				//RR型
				L(root);
			}
			else if (getBalance(root->rchild) == 1) {
				//RL型
				R(root->rchild);//R旋转变成RR型
				L(root);//RR左旋
			}
		}
	}
}
int main() {
	int n, v;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &v);
		insert(root, v);
	}
	printf("%d\n", root->v);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值