题目链接:1123 Is It a Complete AVL Tree (30分)
题意
根据给出的序列建一颗平衡二叉树,并判断是否为完全二叉树
分析
构建平衡二叉树基于左单旋和右单旋。平衡因子的的绝对值超过1.左子树减去右子树的绝对值。
平衡因子为2
- 若左子树的平衡因子为1则进行右单旋。
- 若左子树的平衡因子为-1则先对左子树进行左单旋,在对本树进行右单旋。
平衡因子为-2 - 若右子树的平衡因子为-1则进行左单旋。
- 若右子树的平衡因子为1则先对右子树进行右单旋,在对本树进行左单旋。
深搜判断是否为完全二叉树。
代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct Tree{
int data;
struct Tree *ltree, *rtree;
}Tree;
int maxVal = 0;
void dfs(Tree *root, int index);
void bfs(Tree *root);
void addNode(Tree *&root, int x);
int getFac(Tree *root);
void RR(Tree *&root);
void LL(Tree *&root);
int getHigh(Tree *root);
int main(int argc, char** argv) {
int n, x;
scanf("%d", &n);
Tree *root = NULL;
for (int i = 0; i < n; i++) {
scanf("%d", &x);
addNode(root, x);
}
bfs(root);
dfs(root, 1);
if (maxVal == n)
printf("YES\n");
else
printf("NO\n");
return 0;
}
void dfs(Tree *root, int index) {
if (root == NULL)
return ;
if (index > maxVal) {
maxVal = index;
}
if (root->ltree)
dfs(root->ltree, index * 2);
if (root->rtree)
dfs(root->rtree, index * 2 + 1);
}
void bfs(Tree *root) {
queue<Tree*> que;
que.push(root);
int cnt = 0;
while(!que.empty()) {
cnt++;
Tree *base = que.front();
que.pop();
if (base->ltree)
que.push(base->ltree);
if (base->rtree)
que.push(base->rtree);
if (cnt == 1)
printf("%d", base->data);
else
printf(" %d", base->data);
}
printf("\n");
}
void addNode(Tree *&root, int x) {
if (root == NULL) {
root = (Tree *) malloc(sizeof(Tree));
root->data = x;
root->ltree = root->rtree = NULL;
return ;
}
if (root->data > x) {
addNode(root->ltree, x);
if (getFac(root) == 2) {
if (getFac(root->ltree) == 1) {
RR(root);
} else if (getFac(root->ltree) == -1) { // LR
LL(root->ltree);
RR(root);
}
}
} else {
addNode(root->rtree, x);
if (getFac(root) == -2) {
if (getFac(root->rtree) == 1) { // RL
RR(root->rtree);
LL(root);
} else if (getFac(root->rtree) == -1) {
LL(root);
}
}
}
}
int getFac(Tree *root) {
return getHigh(root->ltree) - getHigh(root->rtree);
}
void RR(Tree *&root) {
Tree *t = root->ltree;
root->ltree = t->rtree;
t->rtree = root;
root = t;
}
void LL(Tree *&root) {
Tree *t = root->rtree;
root->rtree = t->ltree;
t->ltree = root;
root = t;
}
int getHigh(Tree *root) {
if (root == NULL)
return 0;
int l = getHigh(root->ltree);
int r = getHigh(root->rtree);
return l > r ? l + 1 : r + 1;
}