You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于二叉树的单词统计程序运行异常,请求排查

问题分析与修复

核心bug:二叉树节点未正确挂载

你的程序仅统计第一个单词,是因为search函数的逻辑错误——新创建的节点没有被挂载到二叉树的父节点上,导致除根节点外的所有节点都游离在树结构之外,最终print函数只能遍历到根节点。

具体问题点:

  1. search函数递归逻辑错误:当递归到NULL节点时,生成新节点但仅在当前递归栈中返回该节点,没有将其赋值给上层父节点的left或right指针,导致新节点无法加入树结构。
  2. print函数缺乏空指针判断:如果树为空(或节点指针为NULL),直接访问node->left会触发崩溃,存在运行隐患。
  3. main函数根节点跟踪冗余:依赖全局变量first跟踪根节点,不如局部变量node可靠。

修复后的代码

修正search函数

struct bt_node *search(char *word, struct bt_node *node)
{
    struct bt_node *generate_node(char *word);
    if (node == NULL)
        return generate_node(word); // 返回新节点,供上层挂载到父节点

    int comp = strcmp(word, node->word);
    if (comp == 0)
        return node; // 找到目标节点,直接返回
    else if (comp > 0)
        node->right = search(word, node->right); // 将新节点挂载到右子树
    else
        node->left = search(word, node->left); // 将新节点挂载到左子树
    return node;
}

修正print函数

void print(struct bt_node *node)
{
    if (node == NULL)
        return; // 空节点直接返回,避免崩溃
    print(node->left);
    printf("%4d\t%s\n", node->count, node->word);
    print(node->right);
}

修正main函数

int main()
{
    int getword(char *, int);
    struct bt_node *search(char *word, struct bt_node *node), *node = NULL;
    void print(struct bt_node *node);
    struct bt_node *found_node;

    int lim = 100;
    char word[lim];

    while (getword(word, lim) != EOF) {
        if (!(isalpha(word[0]) || word[0] == '_'))
            continue;
        found_node = search(word, node);
        if (node == NULL) {
            // 首次插入,初始化根节点
            node = found_node;
        }
        found_node->count++;
    }
    
    print(node);

    return 0;
}

移除多余全局变量

删除以下全局定义(main不再依赖它):

struct bt_node *first = bt_allocbuf;

同时删除main中的extern struct bt_node *first;声明。

修复后测试

运行./a.out <file.input,会得到正确输出:

3    First_word
   1    Forth_word
   1    Second_word
   1    Third_word

内容的提问来源于stack exchange,提问作者hansoko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 10:54:52