我编写了一个程序,它将两个文件名作为参数f1和f2,这两个文件都带有数字。 该程序应可调用如下:树f1 f2在二进制搜索树中执行删除操作c
f1拥有数百万的唯一编号,每行一个。每个数字应被读取并插入二进制搜索树。
这些插入后,程序应该从第二个文件读取数字。对于每个号,下面有许多工作要做:
- 搜索树
- 如果它存在的号码,询问用户从树中删除它现在
,我的代码对于插入和搜索,正在给出正确的结果,但是,在删除部分中,存在一些错误。
请帮我修改我的代码:
#include <stdio.h>
#include <stdlib.h>
struct node {
int info;
struct node *left, *right;
};
struct node *insert (struct node *root, int item)
{
struct node *temp, *temp1, *pre;
temp = (struct node *) malloc (sizeof (struct node));
temp->info = item;
temp->left = temp->right = NULL;
if (root == NULL)
root = temp;
else {
temp1 = root;
while (temp1 != NULL) {
pre = temp1;
if (item < temp1->info)
temp1 = temp1->left;
else
temp1 = temp1->right;
}
if (item < pre->info)
pre->left = temp;
else
pre->right = temp;
}
return root;
}
struct node *create (struct node *root)
{
int num;
root = NULL;
FILE *fp1 = fopen ("myFile1.txt", "r");
if (fp1 == NULL) {
printf ("cannot open this file");
exit (0);
}
while (fscanf (fp1, "%d", &num) == 1)
root = insert (root, num);
return root;
fclose (fp1); /* (note: unreachable code) */
}
struct node *min (struct node *ptr)
{
struct node *current = ptr;
while (current->left != NULL)
current = current->left;
return current;
}
struct node *delete (struct node *root, int n)
{
if (root == NULL)
return root;
if (n < root->info)
root->left = delete (root->left, n);
else if (n > root->info)
root->right = delete (root->right, n);
else {
if (root->left == NULL) {
struct node *p;
p = root->right;
free (root);
return p;
}
else if (root->right == NULL) {
struct node *p;
p = root->left;
free (root);
return p;
}
struct node *p;
p = min (root->right);
root->info = p->info;
root->right = delete (root->right, p->info);
}
return root;
}
void search (struct node *root)
{
int Y, X;
struct node *t;
t = root;
char ch = 'n';
FILE *fp2 = fopen ("myFile2.txt", "r");
if (fp2 == NULL) {
printf ("cannot open this file");
exit (0);
}
X = 0;
while (fscanf (fp2, "%d", &Y) == 1) {
while (t != NULL && X == 0) {
if (Y == t->info) {
X = 1;
break;
} else if (Y < t->info)
t = t->left;
else
t = t->right;
}
if (X == 1)
printf (" %d is found %d\n", Y, X);
printf ("if you want to delete a number ");
scanf ("%c", &ch);
if (ch == 'y') {
root = delete (root, Y);
return root;
}
else
printf ("%dNot found %d\n", Y, X);
}
fclose (fp2);
}
void inorder (struct node *root)
{
if (root != NULL) {
inorder (root->left);
printf ("%d ", root->info);
inorder (root->right);
}
}
void main()
{
struct node *root = NULL;
struct node *ptr = NULL;
root = create (root);
inorder (root);
search (root);
inorder (root);
}
有些错误?什么是错误? –
你的函数'delete'看起来很好。 – Rabbid76
你用调试器完成了吗? – pm100