- AVL插入操作、包括RR、LL、RL、LR操作。
- 如果一个结点有右孩子但没有左孩子,则不是完全树。
- 如果出现一个孩子数少于2的结点后,又出现有孩子的结点,则不是完全树。
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;
struct node {
int key, height;
node *left, *right;
};
inline int getheight(node *root) {
if (root) {
return root->height;
}
else {
return -1;
}
}
inline int max(int h1, int h2) {
return h1 > h2 ? h1 : h2;
}
node *LL(node *root) {
node *a, *b, *c;
a = root;
b = root->left;
c = b->left;
a->left = b->right;
b->right = a;
if (a) {
a->height = max(getheight(a->left), getheight(a->right)) + 1;
}
if (c) {
c->height = max(getheight(c->left), getheight(c->right)) + 1;
}
return b;
}
node *RR(node *root) {
node *a, *b, *c;
a = root;
b = a->right;
c = b->right;
a->right = b->left;
b->left = a;
if (a) {
a->height = max(getheight(a->left), getheight(a->right)) + 1;
}
if (c) {
c->height = max(getheight(c->left), getheight(c->right)) + 1;
}
return b;
}
node *LR(node *root) {
root->left = RR(root->left);
return LL(root);
}
node *RL(node *root) {
root->right = LL(root->right);
return RR(root);
}
node *insert(node *root, int key) {
if (!root) {
root = new node;
root->key = key;
root->height = 0;
root->left = root->right = nullptr;
}
else {
if (root->key > key) {
root->left = insert(root->left, key);
}
else {
root->right = insert(root->right, key);
}
int h1, h2;
h1 = getheight(root->left);
h2 = getheight(root->right);
if (h1 > h2 + 1) {
int h3, h4;
h3 = getheight(root->left->left);
h4 = getheight(root->left->right);
if (h3 > h4) {
root = LL(root);
}
else {
root = LR(root);
}
}
else if(h1 + 1 < h2) {
int h3, h4;
h3 = getheight(root->right->left);
h4 = getheight(root->right->right);
if (h4 > h3) {
root = RR(root);
}
else {
root = RL(root);
}
}
root->height = max(getheight(root->left), getheight(root->right)) + 1;
}
return root;
}
bool levelorder(node *root) {
queue<node *> q;
node *tmp;
bool leave = false, complete = true;
q.push(root);
printf("%d", root->key);
while (!q.empty()) {
tmp = q.front();
q.pop();
if (tmp->left) {
q.push(tmp->left);
printf(" %d", tmp->left->key);
}
if (tmp->right) {
q.push(tmp->right);
printf(" %d", tmp->right->key);
}
if (!tmp->left && tmp->right) {
complete = false;
}
if (leave && (tmp->right || tmp->left)) {
complete = false;
}
if (!tmp->right || !tmp->left) {
leave = true;
}
}
putchar('\n');
return complete;
}
int main(void)
{
int n, i, tmp;
node *root = nullptr;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &tmp);
root = insert(root, tmp);
}
bool complete;
complete = levelorder(root);
if (complete) {
puts("YES");
}
else {
puts("NO");
}
return 0;
}