【PAT甲级】1066 Root of AVL Tree (25 分)

一、题目分析

1. 翻译

rotation:旋转

2. 关键点

1)掌握AVL树的基础操作,如初始化、获取结点高度、获取平衡因子、更新结点高度、左旋、右旋、插入、建立等等。(详见代码)
2)不要连续使用“->”读取指针所指的内容,如root->lchild->height
3)针对这道题,可以直接用试探法,即直接穷举所有可能出现的情况,详见PAT甲级1066试探法满分
4)考试过程中,做不出来,可以直接蒙中位数,能得一些分。

二、代码解析

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <cctype>
#include <unordered_map>
#include <stack>
#include <queue>
using namespace std;
struct node {
	int v,height;
	node *lchild,*rchild;
	node() {}
	node(int x):v(x),height(1),lchild(NULL),rchild(NULL) {}
}*root;

//node* newnode(int v) {
	struct node Node=new node; //new:申请一个node类型的地址空间
//	node* Node=new node;
//	Node->v=v;
//	Node->height=1;
//	Node->lchild=Node->rchild=NULL;
//	return Node;
//}

int getHeight(node* root) {
	if(root==NULL) return 0;
	return root->height;
}

void updateHeight(node* root) {
//	root->height=max(root->lchild->height,root->rchild->height)+1;
	root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}

int getBalanceFactor(node* root) {
	return getHeight(root->lchild)-getHeight(root->rchild);
}

void L(node* &root) { //要改变树的形态,一定记得加引用!
	node *son;
	son=root->rchild;
	root->rchild=son->lchild;
	son->lchild=root;
	updateHeight(son);//记得更新高度!!!!!
	updateHeight(root);
	root=son;
}

void R(node* &root) { //要改变树的形态,一定记得加引用!
	node *son;
	son=root->lchild;
	root->lchild=son->rchild;
	son->rchild=root;
	updateHeight(son);//记得更新高度!!!!!
	updateHeight(root);
	root=son;
}

void insert(node* &root,int v) {
	if(root==NULL) {
		root=new node(v);
		return;
	}
	if(v<root->v) {
		insert(root->lchild,v);
		updateHeight(root);
		if(getBalanceFactor(root)==2) {
			if(getBalanceFactor(root->lchild)==1) { //LL
				R(root);
			} else if(getBalanceFactor(root->lchild)==-1) { //LR
				L(root->lchild);
				R(root);
			}
		}
	} else {
		insert(root->rchild,v);
		updateHeight(root);
		if(getBalanceFactor(root)==-2) {
			if(getBalanceFactor(root->rchild)==1) { //RL
				R(root->rchild);
				L(root);
			} else if(getBalanceFactor(root->rchild)==-1) { //RR
				L(root);
			}
		}
	}
}

//node* create(int n,int data[]) {
//	node* root=new node;
//	for(int i=0; i<n; i++) {
//		insert(root,data[i]);
//	}
//	return root;
//}

int main() {
	int n;
	cin>>n;
	int data[n];
	for(int i=0; i<n; i++) {
		int temp;
		cin>>temp;
		data[i]=temp;
	}
	root=NULL;
	for(int i=0; i<n; i++) {
		insert(root,data[i]);
	}
	cout<<root->v;
	return 0;
}

三、我的疑问

在这里插入图片描述
第5个测试点通过不了,Ծ‸Ծ

如果喜欢我的博客,欢迎点赞、评论、收藏~~谢谢
( * ^ ▽ ^ * ) ~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值