简体   繁体   English

将字符串插入二进制搜索树C

[英]Inserting a string into a Binary Search Tree C

I need to insert strings into a binary search tree but each run through my insert function updates all the nodes and not just the appropriate one. 我需要将字符串插入二叉搜索树,但是通过插入函数运行的每个字符串都会更新所有节点,而不仅仅是适当的节点。 Its required that each word placed in the binary search tree has the exact amount of memory allocated for it (+1 for the NULL pointer). 它要求放置在二进制搜索树中的每个单词都有为其分配的确切内存量(NULL指针为+1)。

Here's the struct being used: 这是使用的结构:

typedef struct node_t{
   char *word;
   struct node_t *left, *right;
} node_t;

Here's how I am passing in the word: 这是我传递单词的方式:

for(i=0; i< original_words -1; i++)
{
    fscanf(ifp, "%s", y);
    head = insert(head, y);
}

And here's my insert function: 这是我的插入函数:

node_t *insert(struct node_t *head, char *word)
{

if(strcmp(head->word, word) > 0)
{

    if(head->left == NULL)
    {
        head->left = create_node(word);
    }
    else
    {
        head->left = insert(head->left, word);
    }
}

else
{
    if(head->right == NULL)
    {
        head->right = create_node(word);
    }
    else
    {
        head->right = insert(head->right, word);
    }
}

return head;

}

EDIT: Heres an example of the input file. 编辑:这是输入文件的示例。

4
-------
bravo
-------
alpha
-------
gamma
-------
delta

Your answer (the insert function) assumes that head has already been defined on first call, it should start with the line: 您的答案( insert函数)假定在第一次调用时已经定义了head ,它应该从以下行开始:

if (head == null) return create_node(word);

This will also save you from the need for the null lines in the code. 这也将使您无需使用代码中的空行。 I'm not sure that this is the issue, but it is one. 我不知道这问题,但它是一个。

Perhaps more important: how does create_node set up word ? 也许更重要: create_node如何设置word If it's something like: 如果是这样的话:

 new_node->word = word

Then all you are doing is creating a collection of pointers to the word pulled out of the file. 然后,您要做的就是创建指向从文件中拉出的单词的指针的集合。 It is quite possible that each reading of a word from the file reads the word into the same piece of memory, so all you are doing is collecting a tree of pointers to the same place in memory. 每次从文件中读取单词很可能会将单词读入同一块内存,因此您要做的就是收集一个指向内存中同一位置的指针树。 It should be something like: 应该是这样的:

 new_node->word = malloc(strlen(word)+1);
 if (new_note->word == null) {FAIL MEMORY LOSS}
 strcpy(new_node->word, word);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM