c - 将字符串插入二叉搜索树 C

标签 c string search binary-tree binary-search-tree

我需要将字符串插入到二叉搜索树中,但每次运行我的插入函数都会更新所有节点,而不仅仅是适当的节点。 它要求放置在二叉搜索树中的每个单词都有为其分配的确切内存量(+1 为 NULL 指针)。

这是正在使用的结构:

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

下面是我传递这个词的方式:

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

这是我的插入函数:

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;

}

编辑:这是输入文件的示例。

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

最佳答案

您的答案(insert 函数)假设 head 已经在第一次调用时定义,它应该以以下行开头:

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

这也将使您无需在代码中使用空行。我不确定这是问题,但确实是一个问题。

也许更重要的是:create_node 是如何设置word 的?如果是这样的:

 new_node->word = word

然后你所做的就是创建一个指向从文件中提取的单词的指针集合。很可能每次从文件中读取一个单词都会将该单词读入同一 block 内存,因此您所做的只是收集一棵指向内存中同一位置的指针树。它应该是这样的:

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

关于c - 将字符串插入二叉搜索树 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15935352/

相关文章:

algorithm - 排序双链表的搜索算法

python - 在 GAE 中组合文本搜索和查询过滤器

c - 程序集 MMX 点积段错误

c - 如何计算在c中使用fread()读取了多少新行?

检查IPC消息队列是否已经存在而不创建它

javascript - 在 Javascript 中从字符串中提取 URL

c# - 向字符串类添加扩展方法 - C#

ios - '[字符串 ]' is not convertible to ' [NSString]'

mysql - MySQL 自然语言搜索未返回预期结果的问题

c - 不同的线程使用不同的策略进行调度