我的方法比较复杂。因为我发现直接存在数组里面旋转的时候貌似要动的范围比较大。没去细究了。
先用链表法建AVL树,然后层序遍历的时候放到数组形式的树里面。因为从1开始的以数组为存储结构的树编号有规律的
父亲节点编号为i
左孩子为2*i
右孩子为2*+1
按这个规律放好,在最后一个元素之前有空元素的,一定不是完全二叉树。
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cstring>
#define MAX 100
#define null -1
using namespace std;
int n;
int ArryTree[MAX];
vector <int> ans;
struct Node {
int data;
Node * Right;
Node * Left;
int pos;
Node() { Right = NULL; Left = NULL; }
};
typedef Node * Tree;
int GetLevel(Tree t) {
if (!t) {
return 0;
}
return max(GetLevel(t->Left), GetLevel(t->Right)) + 1;
}
Tree LL(Tree t) {
Node * temp = t->Left;
t->Left = temp->Right;
temp->Right = t;
return temp;
}
Tree RR(Tree t) {
Node * temp = t->Right;
t->Right = temp->Left;
temp->Left = t;
return temp;
}
Tree RL(Tree t){
t->Right = LL(t->Right);
return RR(t);
}
Tree LR(Tree t) {
t->Left = RR(t->Left);
return LL(t);
}
Tree Insert(int num, Tree t) {
if (!t) {
t = new Node;
t->data = num;
}
else if (num < t->data) { //左子树上
t->Left = Insert(num, t->Left);
if (GetLevel(t->Left) - GetLevel(t->Right) == 2) {
if (num < t->Left->data) {
t=LL(t);
}
else
t=LR(t);
}
}
else if (num > t->data) {//右子树
t->Right = Insert(num, t->Right);
if (GetLevel(t->Left) - GetLevel(t->Right) == -2) {
if (num > t->Right->data) {
t=RR(t);
}
else
t=RL(t);
}
}
return t;
}
void levelorder(Tree t) {
queue <Tree> q;
if (t) {
t->pos = 1;
q.push(t);
while (!q.empty()) {
Tree tempNode = q.front();
ans.push_back(tempNode->data);
ArryTree[tempNode->pos] = tempNode->data;
q.pop();
if (tempNode->Left) tempNode->Left->pos = tempNode->pos * 2, q.push(tempNode->Left);
if (tempNode->Right) tempNode->Right->pos = tempNode->pos * 2 + 1, q.push(tempNode->Right);
}
}
}
int main() {
cin >> n;
int temp;
Tree t = NULL;
for (int i = 0; i < n; i++) {
cin >> temp;
t = Insert(temp, t);
}
memset(ArryTree, 0, sizeof(ArryTree));
levelorder(t);
for (int i = 0; i < ans.size() - 1; i++) {
cout << ans[i] << " ";
}
cout << ans[ans.size() - 1] << endl;
int last = ans[ans.size() - 1];
bool islast = false;
for (int i = 1; i < MAX; i++) {
if (ArryTree[i] == 0) {
cout << "NO" << endl;
return 0;
}
else if (ArryTree[i] == last) {
break;
}
}
cout << "YES" << endl;
return 0;
}