题目链接:点击打开链接
思路:先按照AVL树的建树规则创建一棵二叉搜索树,得到层序遍历后,判断是否为完全二叉树,完全二叉树的判断方法为:逐层遍历每个节点,当遇到一个空节点,若仍然有未遍历的非空节点,说明不是完全二叉树。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <queue>
using namespace std;
int root,data[25],le[25],rig[25];
int getHeight(int loc){
if(!loc){
return 1;
}
int h1 = getHeight(le[loc]);
int h2 = getHeight(rig[loc]);
return (h1>h2?h1:h2) + 1;
}
void leftSingleRotate(int &r){
int t = le[r];
le[r] = rig[t];
rig[t] = r;
r = t;
return;
}
void rightSingleRotate(int &r){
int t = rig[r];
rig[r] = le[t];
le[t] = r;
r = t;
return;
}
void leftRightRotate(int &r){
rightSingleRotate(le[r]);
leftSingleRotate(r);
return;
}
void rightLeftRotate(int &r){
leftSingleRotate(rig[r]);
rightSingleRotate(r);
return;
}
void add(int &r,int loc){
int h1,h2;
if(!r){
r = loc;
le[r] = rig[r] = 0;
return;
}
else if(data[loc] < data[r]){
add(le[r],loc);
h1 = getHeight(le[r]);
h2 = getHeight(rig[r]);
if(abs(h1 - h2) >= 2){
if(data[loc] < data[le[r]]){//left-single-rotate
leftSingleRotate(r);
}
else{//left-right-double-rotate
leftRightRotate(r);
}
}
}
else{
add(rig[r],loc);
h1 = getHeight(le[r]);
h2 = getHeight(rig[r]);
if(abs(h1 - h2) >= 2){
if(data[loc] > data[rig[r]]){//right-single-rotate
rightSingleRotate(r);
}
else{//right-left-double-rotate
rightLeftRotate(r);
}
}
}
return;
}
void bfs(int r){//层序遍历
queue<int> q;
vector<int> v;
q.push(r);
while(!q.empty()){
int t = q.front();
q.pop();
v.push_back(data[t]);
if(le[t]) q.push(le[t]);
if(rig[t]) q.push(rig[t]);
}
for(int i = 0;i < v.size();i++){
printf("%d%c",v[i],i == v.size() - 1 ? '\n':' ');
}
return;
}
int judge(int r){//判断二叉树是否为完全二叉树
queue<int> q;
q.push(r);
while(!q.empty()){
int t = q.front();
q.pop();
if(!t) break;//遇到空节点
q.push(le[t]);
q.push(rig[t]);
}
while(!q.empty()){
if(q.front() != 0){
return 0;
}
q.pop();
}
return 1;
}
int main(){
int n;
root = 0;
scanf("%d",&n);
for(int i = 1;i <= n;i++){
scanf("%d",&data[i]);
add(root,i);
}
bfs(root);
int flag = judge(root);
puts(flag?"YES":"NO");
return 0;
}