#include <iostream>
#include <queue>
using namespace std;
struct node{
int data;
node *lchild,*rchild;
};
int N;
int geth(node *root){
if(root==NULL) return 0;
return 1+max(geth(root->lchild),geth(root->rchild));
}
int bfac(node *root){
return geth(root->lchild)-geth(root->rchild);
}
void R(node* &root){
node* temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
root=temp;
}
void L(node* &root){
node *temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
root=temp;
}
void createtree(node* &root,int x){
if(root==NULL){
root=new node;
root->data=x;
root->lchild=root->rchild=NULL;
return;
}
if(x<root->data){
createtree(root->lchild,x);
if(bfac(root)==2){
if(bfac(root->lchild)==1){
R(root);
}else if(bfac(root->lchild)==-1){
L(root->lchild);
R(root);
}
}
}else{
createtree(root->rchild,x);
if(bfac(root)==-2){
if(bfac(root->rchild)==-1){
L(root);
}else if(bfac(root->rchild)==1){
R(root->rchild);
L(root);
}
}
}
}
void BFS(node *root){
queue<node*> q;
q.push(root);
int countprint=0;
bool ans=true;
while(!q.empty()){
node* t=q.front();
q.pop();
if(t!=NULL){
printf("%d",t->data);
if(++countprint<N) printf(" ");
}else{
while(!q.empty()&&q.front()==NULL)
q.pop();
if(!q.empty()){
ans=false;
continue;
}else break;
}
q.push(t->lchild);
q.push(t->rchild);
}
if(ans) printf("\nYES");
else printf("\nNO");
}
int main(){
scanf("%d",&N);
node *root=NULL;
for(int i=0;i<N;i++){
int temp;
scanf("%d",&temp);
createtree(root,temp);
}
BFS(root);
return 0;
}
PAT A1123
最新推荐文章于 2024-09-29 22:31:08 发布