[英]What are my errors in this code in C? It's a library catalog that needs to use FILE handling and BST
[英]File handling BST in c
请看下面的代码。 所有输入都是从文件中读取的。 第一行包含X
表示测试用例的数量。 每个测试用例包含 2 行。 第一行包含N
不同的整数(空格分隔)。 第二行包含整数NUM
。 在这段代码中,我需要在单独的中inorder
BST 中显示每个测试用例。
#include <stdio.h>
#include <stdlib.h>
FILE *fp=fopen("file.txt","r");
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;
void insert();
void inorder(struct btnode *t);
void create();
void s(struct btnode *t);
int flag = 1;
void insert()
{
create();
if (root == NULL)
root = temp;
else
s(root);
}
void create()
{
int data;
fscanf(fp,"%d", &data);
temp = (struct btnode *)malloc(1*sizeof(struct btnode));
temp->value = data;
temp->l = temp->r = NULL;
}
void inorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display");
return;
}
if (t->l != NULL)
inorder(t->l);
printf("%d -> ", t->value);
if (t->r != NULL)
inorder(t->r);
}
void s(struct btnode *t)
{
if ((temp->value > t->value) && (t->r != NULL))
s(t->r);
else if ((temp->value > t->value) && (t->r == NULL))
t->r = temp;
else if ((temp->value < t->value) && (t->l != NULL))
s(t->l);
else if ((temp->value < t->value) && (t->l == NULL))
t->l = temp;
}
int main()
{
int ch,n,x;
if(fp==NULL)
{
printf("File Missing");
exit(0);
}
else
{
fscanf(fp,"%d",&x);
for(int j=0;j<x;j++)
{
fscanf(fp,"%d",&n);
for(int i=0;i<n;i++)
{
insert();
}
printf("Set %d: ",j+1);
inorder(root);
printf("\n");
}
}
}
Sample file input:
2
7
4 5 2 77 18 3 6
6
34 3 2 0 6 4
Output:
Set 1: 2 -> 3 -> 4 -> 5 -> 6 -> 18 -> 77 ->
Set 2: 0 -> 2 -> 3 -> 4 -> 6 -> 34 ->
您必须有条件将您的第 1 组和第 2 组分开,并创建多个 BST。 你必须有这个条件 when (i==n) break; 为第二组创建另一个 BST,依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.