//#include "stdafx.h"
#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
#include<set>
#include<queue>
using namespace std;
const int maxn=40;
int n;
struct node{
int height,data;
node*l ,*r;
};
node* newnode(int data){
node* root=new node;
root->data=data;
root->height=1;
root->l=root->r=NULL;
return root;
}
int getheight(node *root){
if(root==NULL)return 0;
else return root->height;
}
void updateheight(node *&root){
root->height=max(getheight(root->l),getheight(root->r))+1;
}
int getbalancefactor(node *root){
return getheight(root->l)-getheight(root->r);
}
void left(node *&root){
node *temp=root->r;
root->r=temp->l;
temp->l=root;
updateheight(root);
updateheight(temp);
root=temp;
}
void right(node *&root){
node *temp=root->l;
root->l=temp->r;
temp->r=root;
updateheight(root);
updateheight(temp);
root=temp;
}
void insert(node *&root,int x){
if(root==NULL)root=newnode(x);
else if(root->data>x){
insert(root->l,x);
updateheight(root);
if(getbalancefactor(root)==2){
if(getbalancefactor(root->l)==1){
right(root);
}
else if(getbalancefactor(root->l)==-1){
left(root->l);
right(root);
}
}}
else{insert(root->r,x);
updateheight(root);
if(getbalancefactor(root)==-2){
if(getbalancefactor(root->r)==-1)
{ left(root);
}
else {
right(root->r);
left(root);
}
}
}
}
int main(){
// freopen("c://jin.txt","r",stdin);
int n;
int a;
node *root=NULL;
cin>>n;
for(int i=0;i<n;i++)
{cin>>a;
insert(root,a);
}
queue<node*>q;
q.push(root);
int num=0;
int flag=0;
while(!q.empty()){//判断是不是一棵完全二叉树:层次遍历,遍历到空之后出现不空 就不是
node* f=q.front();
q.pop();//pop()一定要紧跟q.front();
if(f==NULL){
while(!q.empty()){
f=q.front();
q.pop();
if(f!=NULL){
flag=1;
break;}
}
}
if(f==NULL)break;
cout<<f->data;
num++;
if(num!=n)cout<<" ";
q.push(f->l);
q.push(f->r);
}
cout<<endl;
if(flag)cout<<"NO"<<endl;
else cout<<"YES"<<endl;
// freopen("CON","r",stdin);
// system("pause");
return 0;
}
PAT1123. Is It a Complete AVL Tree (30)(二叉平衡树模板)
最新推荐文章于 2022-06-20 17:20:46 发布