考察点,二叉平衡树、层序遍历和完全二叉树,与1066 Root of AVL Tree (25分)、1064 Complete Binary Search Tree (30分)、1110 Complete Binary Tree (25分)类似,没有难点(代码量比较大,真要在考场上写出这道题一定要对前面几个知识点有比较深的理解)。
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<vector>
using namespace std;
int n, temp,cnt;
bool flag;
struct node {
int value,height;
node *left, *right;
};
int height(node *root) {
return root == NULL ? -1 : root->height;
}
node *ll(node *root) {
node *left = root->left;
root->left = left->right;
left->right = root;
root->height = max(height(root->left),height(root->right))+1;
left->height = max(height(left->left),height(left->right))+1;
return left;
}
node *rr(node *root) {
node *right = root->right;
root->right = right->left;
right->left = root;
root->height = max(height(root->left), height(root->right)) + 1;
right->height = max(height(right->left), height(right->right)) + 1;
return right;
}
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 value) {
if (root == NULL) {
root = new node;
root->value = value;
root->height = 0;
root->left = root->right = NULL;
return root;
}
if (value < root->value) {
root->left = insert(root->left, value);
if (height(root->left) - height(root->right) == 2) {
if (value < root->left->value) root = ll(root);
else root = lr(root);
}
}
else {
root->right = insert(root->right, value);
if (height(root->right) - height(root->left) == 2) {
if (value > root->right->value) root = rr(root);
else root = rl(root);
}
}
root->height = max(height(root->left), height(root->right)) + 1;
return root;
}
int main() {
cin >> n;
node *root =NULL;
for (int i = 0; i < n; i++) {
cin >> temp;
root = insert(root, temp);
}
queue<node*> q;
vector<int> v;
q.push(root);
while (!q.empty()) {
node *r = q.front();
q.pop();
if (r != NULL) {
v.push_back(r->value);
q.push(r->left);
q.push(r->right);
}
else {
flag = true;
continue;
}
cnt++;
if (cnt == n)break;
}
for (int i = 0; i < n; i++) cout << (i == 0 ? "" : " ") << v[i];
cout << endl << (flag?"NO":"YES");
return 0;
}