C元素的C二叉搜索树插入

时间:2016-03-21 09:05:27

标签: c char binary-search-tree insertion

我必须通过在每个节点中插入有关药物的数据来创建二叉搜索树。节点按字符NAME排序。我发现错误,strcmp(name,(*parent)->name) < 0出现分段错误错误。这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct date
{
    int dd,mm,yyyy;
};
typedef struct node
{
    char name[50];
    float price;
    int amount;
    struct date date_rel;
    struct date date_exp;
    struct node *left , *right;
} node;
node *insert_node(node **parent,char name[])
{
    node *current = NULL;
    if(*parent == NULL)
    {
        current = (node *) malloc(sizeof(node));
        strcpy(current->name,name);
        printf("\nPrice =");
        scanf("%f",&current->price);
        printf("\nAmount =");
        scanf("%d",&current->amount);
        printf("\nRelease date =");
        scanf("%d.%d.%d",&current->date_rel.dd,&current->date_rel.mm,&current->date_rel.yyyy);
        printf("\nExpiration date =");
        scanf("%d.%d.%d",&current->date_exp.dd,&current->date_exp.mm,&current->date_exp.yyyy);
        *parent = current;
    }
    else
    {
        if(strcmp(name,(*parent)->name) < 0)
        {
            (*parent)->left = insert_node(&(*parent)->left,name);
        }
        else
        {
            (*parent)->right = insert_node(&(*parent)->right,name);
        }
    }
    return *parent;
}

int main()
{
    node *root = NULL;
    char name[50] ;
    int total_prod;
    printf("The total number of medicines is:");
    scanf("%d",&total_prod);
     while(total_prod != 0)
     {
         printf("Name =");
         scanf("%s",name);
         insert_node(&root,name);
         total_prod--;
     }
    return 0;
}

1 个答案:

答案 0 :(得分:2)

很有可能是因为leftright时您未初始化*parentNULL指针。由于它们未初始化,它们将具有不确定值,并且实际上它将看似随机,并且很可能不等于NULL,这导致您将它们用作有效指针并且您将未定义的行为并获得崩溃。

*parent = current分配之前,您需要将leftright的{​​{1}}和current指针初始化为NULL