1 #include <bits/stdc++.h>
  2 using namespace std;
  3 struct node
  4 {
  5     int data;
  6     node *left;
  7     node *right;
  8     int height;
  9 };
 10 typedef node *AVL;
 11 int get_height(AVL T)
 12 {
 13     if (T == NULL)
 14         return -1;
 15     else
 16         return T->height;
 17 }
 18 
 19 void update_height(AVL T)
 20 {
 21     T->height = max(get_height(T->left), get_height(T->right)) + 1;
 22 }
 23 
 24 AVL single_left(AVL k2)
 25 {
 26     AVL k1 = k2->left;
 27     k2->left = k1->right;
 28     k1->right = k2;
 29     update_height(k2);
 30     update_height(k1);
 31     return k1;
 32 }
 33 
 34 AVL single_right(AVL k2)
 35 {
 36     AVL k1 = k2->right;
 37     k2->right = k1->left;
 38     k1->left = k2;
 39     update_height(k2);
 40     update_height(k1);
 41     return k1;
 42 }
 43 
 44 AVL double_left(AVL k1)
 45 {
 46     k1->left = single_right(k1->left);
 47     return single_left(k1);
 48 }
 49 
 50 AVL double_right(AVL k1)
 51 {
 52     k1->right = single_left(k1->right);
 53     return single_right(k1);
 54 }
 55 
 56 AVL insert(int x, AVL T)
 57 {
 58     if (T == NULL)
 59     {
 60         AVL T = new node;
 61         T->data = x;
 62         T->height = 0;
 63         T->left = T->right = NULL;
 64         return T;
 65     }
 66     if (x < T->data)
 67     {
 68 
 69         T->left = insert(x, T->left);
 70         if (get_height(T->left) - get_height(T->right) == 2)
 71         {
 72             if (x < T->left->data)
 73                 T = single_left(T);
 74             else
 75                 T = double_left(T);
 76         }
 77     }
 78     else
 79     {
 80         T->right = insert(x, T->right);
 81         if (get_height(T->right) - get_height(T->left) == 2)
 82         {
 83             if (x < T->right->data)
 84                 T = double_right(T);
 85             else
 86                 T = single_right(T);
 87         }
 88     }
 89     update_height(T);
 90     return T;
 91 }
 92 bool flag,isok; int tnum=3;
 93 void lev_print(AVL rt) {
 94     queue <AVL> q;
 95     q.push (rt);
 96     while (!q.empty()) {
 97         AVL tmp=q.front(); q.pop();
 98         if (flag) cout<<" ";
 99         else      flag=1;
100         cout<<tmp->data;
101         int num=0;
102         if (tmp->left!=NULL) { q.push(tmp->left); num+=1; }
103         if (tmp->right!=NULL) { q.push(tmp->right); num+=2; }
104         if (num==2||num>tnum) isok=0;
105         tnum=num;
106     }
107 }
108 int main()
109 {
110     int n;
111     cin >> n;
112     AVL rt = NULL;
113     for (int i = 1; i <= n; i++)
114     {
115         int x;
116         cin >> x;
117         rt = insert(x, rt);
118     }
119     isok=1;
120     lev_print(rt); cout<<"\n";
121     if (isok) cout<<"YES\n";
122     else      cout<<"NO\n";
123     return 0;
124 }