这题出的很经典,也很直白,考察三点:AVL树的构造、树的层序遍历、完全二叉树的判断。
没想到不看书不上网这题居然被我搓出来了…本来AVL我已经忘得一干二净,但是之前有道题也考察了AVL,所以当时就顺带复习了一下,今天就写的很快很顺利了,果然刷题还是很有帮助的。
#include<stdio.h>
#include<algorithm>
#include<stdlib.h>
#include<memory.h>
#include<queue>
using namespace std;
typedef struct Node* Tree;
struct Node
{
int value;
Tree left;
Tree right;
int height;
};
Tree singleLeftRotate(Tree A)
{
Tree B = A->left;
Tree C = B->right;
B->right = A;
A->left = C;
int leftHeight = (A->left == NULL) ? 0 : A->left->height;
int rightHeight = (A->right == NULL) ? 0 : A->right->height;
A->height = max(leftHeight, rightHeight) + 1;
return B;
}
Tree singleRightRotate(Tree A)
{
Tree B = A->right;
Tree C = B->left;
B->left = A;
A->right = C;
int leftHeight = (A->left == NULL) ? 0 : A->left->height;
int rightHeight = (A->right == NULL) ? 0 : A->right->height;
A->height = max(leftHeight, rightHeight) + 1;
return B;
}
Tree doubleLeftRotate(Tree A)
{
A->left = singleRightRotate(A->left);
A = singleLeftRotate(A);
return A;
}
Tree doubleRightRotate(Tree A)
{
A->right = singleLeftRotate(A->right);
A = singleRightRotate(A);
return A;
}
Tree insert(int x, Tree T)
{
if (T == NULL)
{
T = (Tree)malloc(sizeof(Node));
T->value = x;
T->left = T->right = NULL;
T->height = 1;
}
else
{
if (x < T->value)
{
T->left = insert(x, T->left);
if (T->left->height - ((T->right == NULL) ? 0 : T->right->height) > 1)
{
if (x < T->left->value)
{
T = singleLeftRotate(T);
}
else
{
T = doubleLeftRotate(T);
}
}
}
else if (x > T->value)
{
T->right = insert(x, T->right);
if (T->right->height - ((T->left == NULL) ? 0 : T->left->height) > 1)
{
if (x > T->right->value)
{
T = singleRightRotate(T);
}
else
{
T = doubleRightRotate(T);
}
}
}
}
int leftHeight = (T->left == NULL) ? 0 : T->left->height;
int rightHeight = (T->right == NULL) ? 0 : T->right->height;
T->height = max(leftHeight, rightHeight) + 1;
return T;
}
bool levelTraversal(Tree root, int* ans)
{
int size = 0;
bool isCompelet = true, semi = false;
queue<Tree> Q;
Q.push(root);
while (Q.empty() == false)
{
ans[size++] = Q.front()->value;
if (Q.front()->left != NULL)
{
Q.push(Q.front()->left);
}
if (Q.front()->right != NULL)
{
Q.push(Q.front()->right);
}
if (semi && (Q.front()->left != NULL || Q.front()->right != NULL))
{
isCompelet = false;
}
if (Q.front()->left == NULL&&Q.front()->right != NULL)
{
isCompelet = false;
}
if (!semi && (Q.front()->left == NULL || Q.front()->right == NULL))
{
semi = true;
}
Q.pop();
}
return isCompelet;
}
int main()
{
int N;
scanf("%d", &N);
Tree T = NULL;
for (int i = 0; i < N; i++)
{
int value;
scanf("%d", &value);
T = insert(value, T);
}
int ans[30];
bool isComplete = levelTraversal(T, ans);
for (int i = 0; i < N; i++)
{
if (i == N - 1)
{
printf("%d\n", ans[i]);
}
else
{
printf("%d ", ans[i]);
}
}
if (isComplete)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
return 0;
}