题意:构造一颗平衡二叉树,求AVL树的层序遍历并判断是否是一颗完全二叉树
思路:考察构造AVL树及判断是否是完全二叉树,构造平衡二叉树前面一个题目有涉及,PAT甲级1066,在层次遍历的时候发现第一个左右孩子为空的时候置标志位为1,然后判断后序还是否存在孩子节点不为空的情况
代码:
#include<iostream>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
typedef struct node {
int data;
struct node *lchild, *rchild;
}*pNode,*tree;
void L_Rotate(pNode &T) {//左旋转
pNode rc = T->rchild;
T->rchild = rc->lchild;
rc->lchild = T;
T = rc;
}
void R_Rotate(pNode &T) {//右旋转
pNode lc = T->lchild;
T->lchild = lc->rchild;
lc->rchild = T;
T = lc;
}
void LeftBalance(pNode &T) {
L_Rotate(T->lchild);
R_Rotate(T);
}
void RightBalance(pNode &T) {
R_Rotate(T->rchild);
L_Rotate(T);
}
int getHeight(pNode T) {//得到该节点在树中的高度
if (T == NULL)return 0;
int l = getHeight(T->lchild);
int r = getHeight(T->rchild);
return max(l, r) + 1;
}
void InsertAVL(pNode &T,int value) {
if (T == NULL) {
T = (pNode)malloc(sizeof(node));
T->data = value;
T->lchild = T->rchild = NULL;
return;
}
if (value < T->data) {
InsertAVL(T->lchild,value);
int l = getHeight(T->lchild), r = getHeight(T->rchild);
if (l - r >= 2) {//如果左子树和右子树高度差大于等于2时
if (value < T->lchild->data) {//当在左子树插入左子树时
R_Rotate(T);
}
else {
LeftBalance(T);
}
}
}
else {
InsertAVL(T->rchild,value);
int l = getHeight(T->lchild), r = getHeight(T->rchild);
if (r - l >= 2) {//如果左子树和右子树高度差大于等于2时
if (value > T->rchild->data) {//当在左子树插入左子树时
L_Rotate(T);
}
else {
RightBalance(T);
}
}
}
}
int after = 0, isComplete = 1;
vector<int> levelOrder(pNode T) {
vector<int> p;
queue<pNode> q;
q.push(T);
while (!q.empty()) {
pNode tem = q.front();
p.push_back(tem->data);
q.pop();
if (tem->lchild != NULL) {
if (after)isComplete = 0;//发现了第一个空的节点之后仍然还有节点的孩子不为空则不是完全二叉树
q.push(tem->lchild);
}
else {
after = 1;//当发现第一个为空的节点的时候
}
if (tem->rchild != NULL) {
if (after)isComplete = 0;
q.push(tem->rchild);
}
else {
after = 1;
}
}
return p;
}
int main() {
int n = 0,temp = 0;
tree T = NULL;
cin >> n;
for (int i = 0; i < n; i++) {
scanf("%d",&temp);
InsertAVL(T,temp);
}
vector<int> p = levelOrder(T);
for (int i = 0; i < p.size(); i++) {
printf("%d%s", p[i], i == p.size() - 1 ? "\n" : " ");
}
printf("%s\n",isComplete==1?"YES":"NO");
system("pause");
return 0;
}