1123 Is It a Complete AVL Tree (30 分)
模板题
#include <iostream>
using namespace std;
int tree[500];
struct node{
int val;
struct node *left, *right;
};
node *rotateLeft(node *root) {
node *t = root->right;
root->right = t->left;
t->left = root;
return t;
}
node *rotateRight(node *root) {
node *t = root->left;
root->left = t->right;
t->right = root;
return t;
}
node *rotateLeftRight(node *root) {
root->left = rotateLeft(root->left);
return rotateRight(root);
}
node *rotateRightLeft(node *root) {
root->right = rotateRight(root->right);
return rotateLeft(root);
}
int height(node *root) {
if(root == NULL) return 0;
return max(height(root->left), height(root->right)) + 1;
}
node *insert(node *root, int v) {
if(root == NULL) {
root = new node();
root->val = v;
root->left = root->right = NULL;
} else if(v < root->val){
root->left = insert(root->left, v);
if(height(root->left) - height(root->right) > 1)
root = v < root->left->val ? rotateRight(root) : rotateLeftRight(root);
} else{
root->right = insert(root->right, v);
if(height(root->left) - height(root->right) < -1)
root = v > root->right->val ? rotateLeft(root) : rotateRightLeft(root);
}
return root;
}
void dfs(node *root, int v) {
if(root == NULL) return;
tree[v] = root->val;
dfs(root->left, v * 2);
dfs(root->right, v * 2 + 1);
}
int main() {
int n, x;
cin >> n;
node *root = NULL;
for(int i = 0; i < n; ++i){
cin >> x;
root = insert(root, x);
}
dfs(root, 1);
int f = 1;
for(int i = 1; i <500; ++i){
if(tree[i] == 0 && i <= n) f = 0;
if(tree[i]){
if(i != 1) cout << " ";
cout << tree[i];
}
}
if(f) printf("\nYES");
else printf("\nNO");
}