一、题目分析
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个测试点通过不了,Ծ‸Ծ
如果喜欢我的博客,欢迎点赞、评论、收藏~~谢谢
( * ^ ▽ ^ * ) ~