128 lines
2.9 KiB
C
128 lines
2.9 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
typedef struct Tree {
|
|
int val;
|
|
struct Tree *l, *r;
|
|
struct Tree *parent;
|
|
} Tree;
|
|
|
|
int n;
|
|
int m;
|
|
|
|
void makeTree(Tree *root, int val) {
|
|
if (val < root->val) {
|
|
if (root->l == NULL) {
|
|
root->l = (Tree *)malloc(sizeof(Tree));
|
|
root->l->val = val;
|
|
root->l->l = NULL;
|
|
root->l->r = NULL;
|
|
root->l->parent = root;
|
|
} else {
|
|
makeTree(root->l, val);
|
|
}
|
|
} else {
|
|
if (root->r == NULL) {
|
|
root->r = (Tree *)malloc(sizeof(Tree));
|
|
root->r->val = val;
|
|
root->r->l = NULL;
|
|
root->r->r = NULL;
|
|
root->r->parent = root;
|
|
} else {
|
|
makeTree(root->r, val);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 中序遍历
|
|
void inOrder(Tree *root) {
|
|
if (root == NULL)
|
|
return;
|
|
inOrder(root->l);
|
|
printf("%d ", root->val);
|
|
inOrder(root->r);
|
|
}
|
|
|
|
// 二叉排序树T查找成功的平均查找长度
|
|
double ASL(Tree *root, int level) {
|
|
if (root == NULL)
|
|
return 0;
|
|
return level + ASL(root->l, level + 1) + ASL(root->r, level + 1);
|
|
}
|
|
|
|
// 找到二叉树中值为val的节点并删除
|
|
void delNode(Tree *root, int val) {
|
|
if (root == NULL)
|
|
return;
|
|
if (root->val == val) {
|
|
if (root->l == NULL && root->r == NULL) {
|
|
if (root->parent->l == root) {
|
|
root->parent->l = NULL;
|
|
} else {
|
|
root->parent->r = NULL;
|
|
}
|
|
free(root);
|
|
} else if (root->l == NULL) {
|
|
if (root->parent->l == root) {
|
|
root->parent->l = root->r;
|
|
} else {
|
|
root->parent->r = root->r;
|
|
}
|
|
free(root);
|
|
} else if (root->r == NULL) {
|
|
if (root->parent->l == root) {
|
|
root->parent->l = root->l;
|
|
} else {
|
|
root->parent->r = root->l;
|
|
}
|
|
free(root);
|
|
} else {
|
|
Tree *p = root->r;
|
|
while (p->l != NULL) {
|
|
p = p->l;
|
|
}
|
|
root->val = p->val;
|
|
delNode(p, p->val);
|
|
}
|
|
} else if (root->val > val) {
|
|
delNode(root->l, val);
|
|
} else {
|
|
delNode(root->r, val);
|
|
}
|
|
}
|
|
|
|
void pt(Tree *root) {
|
|
printf("inOrder:\n");
|
|
inOrder(root);
|
|
printf("\n");
|
|
printf("ASL: %lf\n", ASL(root, 1) / n);
|
|
printf("\n");
|
|
}
|
|
|
|
int main() {
|
|
freopen("data.in", "r", stdin);
|
|
scanf("%d", &n);
|
|
Tree *root = (Tree *)malloc(sizeof(Tree));
|
|
root->parent = NULL;
|
|
for (int i = 0; i < n; i++) {
|
|
int val;
|
|
scanf("%d", &val);
|
|
if (i == 0) {
|
|
root->val = val;
|
|
root->l = NULL;
|
|
root->r = NULL;
|
|
} else {
|
|
makeTree(root, val);
|
|
}
|
|
}
|
|
pt(root);
|
|
|
|
scanf("%d", &m);
|
|
for (int i = 0; i < m; i++) {
|
|
int x;
|
|
scanf("%d", &x);
|
|
delNode(root, x);
|
|
pt(root);
|
|
}
|
|
return 0;
|
|
} |