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

C语言结构体实现二叉搜索树失败,求地址关联问题解决方案

二叉搜索树实现问题的修复方案

你的代码核心问题是C语言的参数传递是值传递,add函数里的temp指针只是外部指针的副本,修改它不会影响原指针(比如全局的root或者父节点的left/right),导致新节点永远无法真正挂载到树上,最终root始终是NULL,打印不出任何内容。

修复步骤:

  1. 修改add函数的参数为指针的指针(struct tree **temp),这样才能通过它修改外部的指针变量
  2. 调整函数内的指针访问逻辑,用*temp来操作目标指针

修正后的完整代码:

#include <stdio.h>
#include <stdlib.h>

struct tree{
    int data;
    struct tree *left;
    struct tree *right;
};

struct tree *root = NULL;

void add(int value, struct tree **temp){
    if(*temp == NULL){
        *temp = (struct tree *) malloc(sizeof(struct tree));
        (*temp)->left = NULL;
        (*temp)->right = NULL;
        (*temp)->data = value;
        return;
    }
    else{
        if(value > (*temp)->data){
            add(value, &((*temp)->right));
        }else{
            add(value, &((*temp)->left));
        }
    }
}

void printTree(struct tree *temp){
    if (temp != NULL) {
        printTree(temp->left);
        printf("%d ", temp->data);
        printTree(temp->right);
    }
}

int main(){
    add(4, &root);
    add(2, &root);
    add(3, &root);
    add(1, &root);
    add(6, &root);
    add(7, &root);
    add(5, &root);
    printTree(root);
}

关键修改说明:

  • 调用add时传入指针的地址,比如add(4, &root),这样函数能直接修改root的值
  • 函数内用*temp访问目标指针,比如*temp = malloc(...)就是给外部指针分配内存
  • 递归调用时传入子节点指针的地址,比如&((*temp)->right),确保子节点能正确挂载到父节点上

运行修正后的代码,会输出1 2 3 4 5 6 7,符合二叉搜索树的中序遍历结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:42:50