【发布时间】:2016-02-02 15:58:43
【问题描述】:
我编写了一个程序,它将两个文件名作为参数,f1 和 f2,这两个文件都带有数字。 该程序应该可以如下调用:tree f1 f2
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);
}
【问题讨论】:
-
一些错误?错误是什么?
-
你用调试器单步调试了吗?
-
您有机会查看答案吗?
标签: c binary-search-tree