通过char元素插入C二叉搜索树

C binary search tree insertion by char element

我必须通过在每个节点中插入有关药物的数据来创建二叉搜索树。节点按 char 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;
}

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

*parent = current赋值之前,您需要将currentleftright指针初始化为NULL