本题考查了AVL树的建立,插入,左旋,右旋等一系列基本操作,还有二叉树的层序遍历,完全二叉树的性质这些知识点
其实就是在PAT (Advanced Level) Practice 1066 Root of AVL Tree的基础上增加层序遍历以及完全二叉树的判断
题目 PAT (Advanced Level) Practice 1066 Root of AVL Tree
题目 PAT (Advanced Level) Practice 1123 Is It a Complete AVL Tree
再来复习一下完全二叉树的性质,以下摘自《算法笔记》
对完全二叉树当中的任何一个结点(设编号为x),其左孩子的编号一定是2x,而右孩子的编号一定是2x+1。也就是说,完全二叉树可以通过建立一个大小为2^k的数组来存放所有结点的信息,其中k为完全二叉树的最大高度,且1号位存放的必须是根结点。该数组中元素存放的顺序恰好为该完全二叉树的层序遍历序列。
而判断某个结点是否为叶结点的标志为:该结点(记下标为root)的左子结点的编号为root*2大于结点总个数为n;判断某个结点是否为空结点的标志为:该结点下标root大于结点总个数n
上学期学习AVL树的时候,始终都没有理解《算法笔记》上的内容。这次,在较为完整地学习完BST后,对于AVL树有了进一步的理解。毕竟AVL树是建立在BST的基础上。
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn=22;
int a[maxn], b[maxn];
int n;
struct node{
int data, height;
node *lchild, *rchild;
};
int getHeight(node* root){
if(root==NULL)
return 0;
else
return root->height;
}
int getBalanceFactor(node* root){
return getHeight(root->lchild)-getHeight(root->rchild);
}
void updateHeight(node* root){
root->height=max(getHeight(root->lchild), getHeight(root->rchild))+1;
}
void L(node* &root){
node* temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
updateHeight(root);
updateHeight(temp);
root=temp;
}
void R(node* &root){
node* temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
updateHeight(root);
updateHeight(temp);
root=temp;
}
node* newnode(int x){
node* Node=new node;
Node->data=x;
Node->height=1;
Node->lchild=Node->rchild=NULL;
return Node;
}
void insert(node* &root, int x){
if(root==NULL){
root=newnode(x);
return;
}
if(root->data>x){
insert(root->lchild, x);
updateHeight(root);
if(getBalanceFactor(root)==2){
if(getBalanceFactor(root->lchild)==1){
R(root);
} else if(getBalanceFactor(root->lchild)==-1){
L(root->lchild);
R(root);
}
}
} else {
insert(root->rchild, x);
updateHeight(root);
if(getBalanceFactor(root)==-2){
if(getBalanceFactor(root->rchild)==-1){
L(root);
} else if(getBalanceFactor(root->rchild)==1){
R(root->rchild);
L(root);
}
}
}
}
node* create(int data[], int n){
node* root=NULL;
for(int i=0; i<n; i++)
insert(root, data[i]);
return root;
}
int index=1, num=0;
bool flag=true;
void bfs(node* root){
queue<node*> q;
q.push(root);
while(!q.empty()){
node* front=q.front();
q.pop();
b[num++]=front->data;
if(a[index]!=b[num-1]){
//printf("%d %d %d %d\n", index, num, a[index], b[num-1]);
flag=false;
}
if(front->lchild!=NULL){
a[2*index]=front->lchild->data;
q.push(front->lchild);
} else {
a[2*index]=-1;
}
if(front->rchild!=NULL){
a[2*index+1]=front->rchild->data;
q.push(front->rchild);
} else {
a[2*index+1]=-1;
}
index+=1;
}
}
int main()
{
int d[maxn];
scanf("%d", &n);
for(int i=0; i<n; i++)
scanf("%d", &d[i]);
node* root=create(d, n);
a[1]=root->data;
bfs(root);
for(int i=0; i<num; i++){
printf("%d", b[i]);
printf(i+1!=num ? " " : "\n");
}
if(flag)
printf("YES\n");
else
printf("NO\n");
return 0;
}