106 lines
2.5 KiB
C
106 lines
2.5 KiB
C
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
|
||
int n;
|
||
int m;
|
||
// 二叉排序树,根节点为 1,左子树为 2 * i,右子树为 2 * i + 1
|
||
int tree[1000];
|
||
|
||
void makeTree(int val) {
|
||
int r = 1;
|
||
while (1) {
|
||
if (val < tree[r]) {
|
||
if (tree[2 * r] == 0) {
|
||
// printf("r: %d, val: %d\n", 2 * r, val);
|
||
tree[2 * r] = val;
|
||
break;
|
||
} else {
|
||
r = 2 * r;
|
||
}
|
||
} else {
|
||
if (tree[2 * r + 1] == 0) {
|
||
// printf("r: %d, val: %d\n", 2 * r + 1, val);
|
||
tree[2 * r + 1] = val;
|
||
break;
|
||
} else {
|
||
r = 2 * r + 1;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 中序遍历
|
||
void inOrder(int root) {
|
||
if (tree[2 * root] != 0)
|
||
inOrder(2 * root);
|
||
printf("%d ", tree[root]);
|
||
if (tree[2 * root + 1] != 0)
|
||
inOrder(2 * root + 1);
|
||
}
|
||
|
||
// 二叉排序树T查找成功的平均查找长度
|
||
double ASL(int root, int level) {
|
||
if (tree[root] == 0)
|
||
return 0;
|
||
return level + ASL(2 * root, level + 1) + ASL(2 * root + 1, level + 1);
|
||
}
|
||
|
||
// 找到二叉树中值为val的节点并删除
|
||
void delNode(int root, int x) {
|
||
if (tree[root] == 0)
|
||
return;
|
||
if (tree[root] == x) {
|
||
if (tree[2 * root] == 0 && tree[2 * root + 1] == 0) {
|
||
tree[root] = 0;
|
||
} else if (tree[2 * root] != 0 && tree[2 * root + 1] == 0) {
|
||
tree[root] = tree[2 * root];
|
||
tree[2 * root] = 0;
|
||
} else if (tree[2 * root] == 0 && tree[2 * root + 1] != 0) {
|
||
tree[root] = tree[2 * root + 1];
|
||
tree[2 * root + 1] = 0;
|
||
} else {
|
||
int r = 2 * root + 1;
|
||
while (tree[2 * r] != 0) {
|
||
r = 2 * r;
|
||
}
|
||
tree[root] = tree[r];
|
||
tree[r] = 0;
|
||
}
|
||
} else if (tree[root] > x) {
|
||
delNode(2 * root, x);
|
||
} else {
|
||
delNode(2 * root + 1, x);
|
||
}
|
||
}
|
||
|
||
void pt() {
|
||
printf("inOrder:\n");
|
||
inOrder(1);
|
||
printf("\n");
|
||
printf("ASL: %lf\n", ASL(1, 1) / n);
|
||
printf("\n");
|
||
}
|
||
|
||
int main() {
|
||
freopen("data.in", "r", stdin);
|
||
scanf("%d", &n);
|
||
for (int i = 1; i <= n; i++) {
|
||
int val;
|
||
scanf("%d", &val);
|
||
if (i == 1) {
|
||
tree[1] = val;
|
||
} else {
|
||
makeTree(val);
|
||
}
|
||
}
|
||
pt();
|
||
|
||
scanf("%d", &m);
|
||
for (int i = 0; i < m; i++) {
|
||
int x;
|
||
scanf("%d", &x);
|
||
delNode(1, x);
|
||
pt();
|
||
}
|
||
return 0;
|
||
} |