Note
Code
#include<bits/stdc++.h>
using namespace std;
struct node{
int data, height;
node *left, *right;
};
node* newnode(int n) {
node* root = new node;
root->data = n;
root->left = root->right = NULL;
return root;
}
int getheight(node* root) {
if(root == NULL) return 0;
return max(getheight(root->left), getheight(root->right)) + 1;
}
int getfactor(node* root) {
if(root == NULL) return 0;
return getheight(root->left) - getheight(root->right);
}
void L(node* &root) {
node *root_right = root->right;
root->right = root_right->left;
root_right->left = root;
root = root_right;
return ;
}
void R(node* &root) {
node *root_left = root->left;
root->left = root_left->right;
root_left->right = root;
root = root_left;
return ;
}
void insert(node* &root, int val) {
if(root == NULL) {
root = newnode(val);
return ;
}
else {
if(val < root->data) {
insert(root->left, val);
}
else {
insert(root->right, val);
}
int fac = getfactor(root);
if(fac == 2) {
int fac_left = getfactor(root->left);
if(fac_left == 1) {
R(root);
}
else if(fac_left == -1) {
L(root->left);
R(root);
}
}
else if(fac == -2) {
int fac_right = getfactor(root->right);
if(fac_right == -1) {
L(root);
}
else if(fac_right == 1) {
R(root->right);
L(root);
}
}
}
}
vector<int> ans;
void bfs(node* root) {
queue<node*> q;
q.push(root);
while(!q.empty()) {
node *t = q.front();
q.pop();
ans.push_back(t->data);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
bool check(node *root, int n, int loc) {
if(root == NULL && loc <= n) return false;
if(root == NULL || loc >= 2 * n + 1) return true;
return check(root->left, n, loc * 2) && check(root->right, n, loc * 2 + 1);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("data.txt", "r", stdin);
#endif
int n, val;
cin >> n;
node *root = NULL;
for(int i = 0; i < n; i++) {
cin >> val;
insert(root, val);
}
bfs(root);
for(int i = 0; i < n; i++) {
if(i != 0) printf(" ");
printf("%d", ans[i]);
}
if(check(root, n, 1)) printf("\nYES");
else printf("\nNO");
return 0;
}