#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct node{
int h, v;
node* L;
node* R;
};
node* newNode(int v){
node* Node = new node;
Node->v = v;
Node->h = 1;
Node->L = Node->R = NULL;
return Node;
}
int getH(node* root){
if(root == NULL) return 0;
return root->h;
}
int getBF(node* root){
return getH(root->L) - getH(root->R);
}
void UpdateH(node* root){
root->h = max(getH(root->R), getH(root->L)) + 1;
}
void L(node* &root){
node* temp = root->R;
root->R = temp->L;
temp->L = root;
UpdateH(root);
UpdateH(temp);
root = temp;
}
void R(node* &root){
node* temp = root->L;
root->L = temp->R;
temp->R = root;
UpdateH(root);
UpdateH(temp);
root = temp;
}
void insert(node* &root, int v){
if(root == NULL){
root = newNode(v);
return;
}
if(v < root->v){
insert(root->L, v);
UpdateH(root);
if(getBF(root) == 2){
if(getBF(root->L) == 1){
R(root);
}else if(getBF(root->L) == -1){
L(root->L);
R(root);
}
}
}else{
insert(root->R, v);
UpdateH(root);
if(getBF(root) == -2){
if(getBF(root->R) == -1){
L(root);
}else if(getBF(root->R) == 1){
R(root->R);
L(root);
}
}
}
}
node* Create(int data[], int n){
node* root = NULL;
for(int i = 0; i < n; i++){
insert(root, data[i]);
}
return root;
}
int isComplete = 1, after = 0;
vector<int> levelOrder(node* root){
vector<int> v;
queue<node*> q;
q.push(root);
while(!q.empty()){
node* temp = q.front();
q.pop();
v.push_back(temp->v);
if(temp->L != NULL){
if(after) isComplete = 0;
q.push(temp->L);
}else{
after = 1;
}
if(temp->R != NULL){
if(after) isComplete = 0;
q.push(temp->R);
}else{
after = 1;
}
}
return v;
}
int main(){
int n, data[25];
scanf("%d", &n);
node* root = NULL;
for(int i = 0; i < n; i++){
scanf("%d", &data[i]);
}
root = Create(data, n);
vector<int> v = levelOrder(root);
for(int i = 0; i < n; i++){
if(i != 0) printf(" ");
printf("%d", v[i]);
}
printf("\n%s", isComplete ? "YES" : "NO");
return 0;
}
A11231123 Is It a Complete AVL Tree (30分)
原文:https://www.cnblogs.com/tsruixi/p/13052439.html