PAT_A_1066 Root of AVL Tree

题意:构造一颗AVL树,输出其根节点

思路:构造AVL树即二叉平衡树,可以参考严奶奶的数据结构构造AVL树,过程差不多,只是没有用平衡因子,直接求出左右孩子的深度,简化了一些对平衡因子的修改,其余思想都差不多

代码:

#include<iostream>
#include<algorithm>
using namespace std;
typedef struct node {
	int data;
	struct node *lchild, *rchild;
}*pNode;
void R_Rotate(pNode &T) {
	pNode lc = T->lchild;
	T->lchild = lc->rchild;
	lc->rchild = T;
	T = lc;
}
void L_Rotate(pNode &T) {
	pNode rd = T->rchild;
	T->rchild = rd->lchild;
	rd->lchild = T;
	T = rd;
}
void LeftBalence(pNode &T) {
	L_Rotate(T->lchild);
	R_Rotate(T);
}
void RightBalence(pNode &T) {
	R_Rotate(T->rchild);
	L_Rotate(T);
}
int getDepth(pNode T) {
	if (T == NULL)return 0;
	int l = getDepth(T->lchild);
	int r = getDepth(T->rchild);
	return max(l, r) + 1;
}
void InsertAVL(pNode &T,int value) {
	if (T == NULL) {
		T = new node();
		T->data = value;
		T->lchild = T->rchild = NULL;
		return;
	}
	if (value < T->data) {
		InsertAVL(T->lchild,value);
		int l = getDepth(T->lchild),r = getDepth(T->rchild);
		if (l - r >= 2) {//当发现第一个不平衡的点的时候开始调整
			if(value<T->lchild->data){//插入到左子树的左子树发现不平衡时
				R_Rotate(T);
			}
			else {
				LeftBalence(T);
			}
		}
	}
	else {
		InsertAVL(T->rchild, value);
		int l = getDepth(T->lchild), r = getDepth(T->rchild);
		if (r - l >= 2) {
			if (value > T->rchild->data) {
				L_Rotate(T);
			}
			else {
				RightBalence(T);
			}
		}
	}
}
int main() {
	int n = 0,tem = 0;
	pNode T = NULL;
	cin >> n;
	for (int i = 0; i < n; i++) {
		scanf("%d",&tem);
		InsertAVL(T,tem);
	}
	cout << T->data << endl;
	system("pause");
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值