思路:建立AVL树+判断完全二叉树,AVL树不会出现退化为很长的链表的情况,所以可以给节点编号,
然后通过层序遍历得出编号序列,判断它们是否连续即可。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
struct Node{
int data,hi,id;
struct Node *Left,*Right;
};
typedef struct Node *Tree;
int MAX(int x,int y)
{
return x>y?x:y;
}
int Height(Tree T)
{
if(T==NULL) return -1;
else return T->hi;
}
Tree LeftRotate(Tree T)
{
Tree p=T->Left;
T->Left=p->Right;
p->Right=T;
T->hi=MAX(Height(T->Left),Height(T->Right))+1;
p->hi=MAX(Height(p->Left),T->hi)+1;
return p;
}
Tree RightRotate(Tree T)
{
Tree p=T->Right;
T->Right=p->Left;
p->Left=T;
T->hi=MAX(Height(T->Left),Height(T->Right))+1;
p->hi=MAX(Height(p->Right),T->hi)+1;
return p;
}
Tree LeftRightRotate(Tree T)
{
T->Left=RightRotate(T->Left);
return LeftRotate(T);
}
Tree RightLeftRotate(Tree T)
{
T->Right=LeftRotate(T->Right);
return RightRotate(T);
}
Tree Insert(int x,Tree T)
{
if(T==NULL){
T=new Node;
T->data=x;
T->Left=NULL;
T->Right=NULL;
T->hi=0;
}
else if(x<T->data){
T->Left=Insert(x,T->Left);
if(Height(T->Left)-Height(T->Right)==2){
if(x<T->Left->data) T=LeftRotate(T);
else T=LeftRightRotate(T);
}
}
else if(x>T->data){
T->Right=Insert(x,T->Right);
if(Height(T->Right)-Height(T->Left)==2){
if(x>T->Right->data) T=RightRotate(T);
else T=RightLeftRotate(T);
}
}
T->hi=MAX(Height(T->Left),Height(T->Right))+1;
return T;
}
vector <int> ans,vc;
void bfs(Tree T)
{
Tree tmp;
T->id=1;
ans.clear();
vc.clear();
queue <Tree> q;
q.push(T);
while(!q.empty()){
tmp=q.front();q.pop();
ans.push_back(tmp->data);
vc.push_back(tmp->id);
if(tmp->Left!=NULL){
tmp->Left->id=tmp->id*2;
q.push(tmp->Left);
}
if(tmp->Right!=NULL){
tmp->Right->id=tmp->id*2+1;
q.push(tmp->Right);
}
}
}
int main(void)
{
int n,i,x;
Tree T=NULL;
cin>>n;
for(i=0;i<n;i++){
cin>>x;
T=Insert(x,T);
}
bfs(T);
int fg=0;
for(i=0,x=ans.size();i<x;i++){
if(i){
cout<<" ";
if(vc[i]-vc[i-1]!=1) fg=1;
}
cout<<ans[i];
}
cout<<endl;
if(fg==0) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
return 0;
}