#include <iostream>
#include <stdlib.h>
#include <queue>
using namespace std;
typedef struct node
{
int key, bf;
struct node *lchild, *rchild;
}*bnode;
queue<bnode> q, temp;
int res = 1, first = 1;
void bfs()
{
int qsize = q.size(), tempsize;
bnode cur, l, r;
while(qsize--)
{
cur = q.front();
q.pop();
if(cur == NULL)
{
temp = q;
tempsize = temp.size();
while(tempsize--)
{
cur = temp.front();
if(cur != NULL)
{
res = 0;
break;
}
}
continue;
}
if(first == 1)
{
first = 0;
}
else
{
printf(" ");
}
printf("%d", cur->key);
l = cur->lchild;
r = cur->rchild;
q.push(l);
q.push(r);
}
qsize = q.size();
if(qsize > 0)
{
bfs();
}
}
void rrotate(bnode *root)
{
bnode l = (*root)->lchild;
bnode lr = l->rchild;
(*root)->lchild = lr;
l->rchild = *root;
*root = l;
}
void lrotate(bnode *root)
{
bnode r = (*root)->rchild;
bnode rl = r->lchild;
(*root)->rchild = rl;
r->lchild = *root;
*root = r;
}
void rbalance(bnode *root)
{
bnode r = (*root)->rchild;
int rbf = r->bf;
bnode rl = r->lchild;
int rlbf;
if(rbf == 1)
{
(*root)->bf = r->bf = 0;
lrotate(root);
}
else if(rbf == -1)
{
rlbf = rl->bf;
if(rlbf == -1)
{
r->bf = 1;
(*root)->bf = 0;
}
else if(rlbf == 1)
{
(*root)->bf = -1;
r->bf = 0;
}
else
{
(*root)->bf = r->bf = 0;
}
rl->bf = 0;
rrotate(&((*root)->rchild));
lrotate(root);
}
}
void lbalance(bnode *root)
{
bnode l = (*root)->lchild;
int lbf = l->bf;
bnode lr = l->rchild;
int lrbf;
if(lbf == -1)
{
(*root)->bf = l->bf = 0;
rrotate(root);
}
else if(lbf == 1)
{
lrbf = lr->bf;
if(lrbf == 1)
{
l->bf = -1;
(*root)->bf = 0;
}
else if(lrbf == -1)
{
(*root)->bf = 1;
l->bf = 0;
}
else
{
(*root)->bf = l->bf = 0;
}
lr->bf = 0;
lrotate(&((*root)->lchild));
rrotate(root);
}
}
void avlinsert(bnode *root, int key, int &taller)
{
int rootkey, rootbf;
if(*root == NULL)
{
*root = (bnode) malloc (sizeof(node));
(*root)->bf = 0;
(*root)->key = key;
(*root)->lchild = (*root)->rchild = NULL;
taller = 1;
}
else
{
rootkey = (*root)->key;
if(key < rootkey)
{
avlinsert(&((*root)->lchild), key, taller);
if(taller == 1)
{
rootbf = (*root)->bf;
if(rootbf == 0)
{
(*root)->bf = -1;
}
else if(rootbf == 1)
{
(*root)->bf = 0;
taller = 0;
}
else
{
lbalance(root);
taller = 0;
}
}
}
else
{
avlinsert(&((*root)->rchild), key, taller);
if(taller == 1)
{
rootbf = (*root)->bf;
if(rootbf == 0)
{
(*root)->bf = 1;
}
else if(rootbf == -1)
{
(*root)->bf = 0;
taller = 0;
}
else
{
rbalance(root);
taller = 0;
}
}
}
}
}
int main()
{
int n;
scanf("%d", &n);
int i, key, taller;
bnode root = NULL;
for(i = 1; i <= n; i++)
{
scanf("%d", &key);
avlinsert(&root, key, taller);
}
q.push(root);
bfs();
printf("\n");
if(res == 1)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
system("pause");
return 0;
}