c 中的文件处理 BST

宁录

请看下面的代码。所有输入都是从文件中读取的。第一行包含X表示测试用例的数量。每个测试用例包含 2 行。第一行包含N不同的整数(空格分隔)。第二行包含整数NUM在这段代码中,我需要在单独的inorderBST 中显示每个测试用例

#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,依此类推。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章