之前我们写过完全二叉树的判断
实际上还有一个更简单的判断方法(这也是完全二叉树的一个性质)
判断一棵树是否为完全二叉树,可以给每个节点编号
例如某个节点编号为
i
d
id
id,左儿子为
2
∗
i
d
2*id
2∗id,右儿子为
2
∗
i
d
+
1
2*id+1
2∗id+1
如果最大的编号为n,即为完全二叉树
平衡二叉树的板子,要好好背过啊
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
using namespace std;
const int N = 25;
struct node {
int data;
node* lc;
node* rc;
int height;
node(int x) {
data = x;
height = 1;
lc = rc = NULL;
}
};
//获取树的高度
int getTreeHeight(node* root) {
if (root == NULL) return 0;
else return root->height;
}
//更新树的高度
void updateTreeHeight(node* root) {
root->height = max(getTreeHeight(root->lc), getTreeHeight(root->rc)) + 1;
}
//获取平衡因子
int getBalanceFactor(node* root) {
return getTreeHeight(root->lc) - getTreeHeight(root->rc);
}
void leftRotate(node* &root) {
node* tmp = root->rc;
root->rc = tmp->lc;
tmp->lc = root;
updateTreeHeight(root);
updateTreeHeight(tmp);
root = tmp;
}
void rightRotate(node* &root) {
node* tmp = root->lc;
root->lc = tmp->rc;
tmp->rc = root;
updateTreeHeight(root);
updateTreeHeight(tmp);
root = tmp;
}
//插入新节点
//因为有new操作所以root需要传引用
void insert(node* &root, int x) {
if (root == NULL) {
root = new node(x);
return;
}
if (x < root->data) {
insert(root->lc, x);
//更新高度
updateTreeHeight(root);
if (getBalanceFactor(root) == 2) { //左子树插入
if (x < root->lc->data) { //LL
rightRotate(root);
}
else { //LR
leftRotate(root->lc);
rightRotate(root);
}
}
}
else {
insert(root->rc, x);
updateTreeHeight(root);
if (getBalanceFactor(root) == -2) { //右子树插入
if (x > root->rc->data) { //RR
leftRotate(root);
}
else { //RL
rightRotate(root->rc);
leftRotate(root);
}
}
}
}
node* Q[N * 2];
int level[N];
void printLevel(node* root) {
if (root == NULL) return;
int tou = 0;
int wei = 0;
int flag = 0;
Q[++wei] = root;
while (tou < wei) {
node* tmp = Q[++tou];
if (!flag) {
printf("%d", tmp->data);
flag = 1;
}
else printf(" %d", tmp->data);
if (tmp->lc) Q[++wei] = tmp->lc;
if (tmp->rc) Q[++wei] = tmp->rc;
}
printf("\n");
}
int maxid = 0;
void solve(node* root, int id) {
maxid = max(maxid, id);
if (root->lc) solve(root->lc, id * 2);
if (root->rc) solve(root->rc, id * 2 + 1);
}
int checkCompleteTree(node* root, int n) {
solve(root, 1);
if (maxid != n) return 0;
else return 1;
}
int main()
{
int n;
scanf("%d",&n);
node* root = NULL;
for (int i = 0; i < n; ++i) {
int x;
scanf("%d", &x);
insert(root, x);
}
if (n == 0) {
printf("NO");
}
else {
printLevel(root);
if (checkCompleteTree(root, n)) printf("YES");
else printf("NO");
}
return 0;
}