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

C语言实现BST高度计算结果不符问题求助

问题分析与解决

你的代码存在两个关键问题,其中一个是导致高度计算错误的核心原因:

1. insert 函数缺少返回值(核心问题)

insert 函数声明返回 struct Node*,但在非空树插入左/右子树的分支中没有返回当前节点指针。C语言中函数未明确返回值时会返回随机值,这会导致上层节点的 left/right 指针被错误赋值为随机值,直接破坏二叉树结构,最终让高度计算结果异常。

修复方法

在 insert 函数的末尾添加返回当前节点的语句:

struct Node* insert(struct Node** root, int data)
{
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));

    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;

    if ((*root)==NULL){
        *root = temp;
        return *root;
    }
    else if (data <= (*root)->data){
        (*root)->left = insert(&((*root)->left), data);
    }
    else {
        (*root)->right = insert(&((*root)->right), data);
    }
    // 新增:返回当前节点,保证上层指针赋值正确
    return *root;
}

2. 高度计算逻辑验证(修复后符合预期)

你的 FindHeight 函数逻辑是正确的:空节点返回0,非空节点返回左右子树高度的最大值加1。当树结构修复后,对应你构建的树:

  • 叶子节点(20、40、60、80)高度为1
  • 中间节点(30、70)高度为2
  • 根节点(50)高度为3,完全符合你的预期。

修复 insert 函数后,代码会正确返回高度3。

内容的提问来源于stack exchange,提问作者Kim Hyun Bin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:15:36