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

C语言实现将BST节点存入数组的BSTtoArr函数求助

问题排查与正确实现

现有代码的核心问题

  • 变量名不匹配:两个实现里都出现了未定义的变量v,你传入的数组参数是arr,应该操作arr而不是v
  • 存储对象错误:函数要求将树节点存入数组,但现有代码存入的是root->data节点值,不符合需求
  • static索引缺陷:第一个版本用static int pos,静态变量只会初始化一次,多次调用函数时pos不会重置为0,会导致数组越界或数据错位
  • 传值索引失效:第二个版本用传值方式传索引i,左子树递归过程中对i的修改不会同步到父层级,右子树会覆盖左子树已经写入的位置
  • 调用逻辑错误:函数声明是BSTtoArr,调用时写成了BSTtoArray,函数名不匹配;如果要存储节点指针,你申请的数组类型错误,应该是Tree**类型而不是Tree*

正确实现(默认中序遍历,可自行调整为前序/后序)

版本1:存储节点指针到数组

// 辅助递归函数,pos用指针传递保证递归过程中索引同步更新
void BSTtoArrHelper(Tree* root, Tree* arr[], int* pos) {
    if (root == NULL) return;
    BSTtoArrHelper(root->left, arr, pos);
    arr[(*pos)++] = root; // 存入节点指针,如需存节点值可修改为 root->data
    BSTtoArrHelper(root->right, arr, pos);
}

// 对外暴露的调用接口
void BSTtoArr(Tree* root, Tree* arr[]) {
    int pos = 0;
    BSTtoArrHelper(root, arr, &pos);
}

对应的调用方式:

int nodeCount = TreeSize(root);
// 申请存储Tree*指针的数组,每个元素存一个节点的地址
Tree** arr = (Tree**)malloc(nodeCount * sizeof(Tree*));
BSTtoArr(root, arr);

// 业务逻辑使用数组...

// 使用完成后释放数组
free(arr);

如果你需要将节点的完整数据拷贝到数组(不是存指针),可以使用以下版本:

版本2:存储节点拷贝到数组

void BSTtoArrHelper(Tree* root, Tree arr[], int* pos) {
    if (root == NULL) return;
    BSTtoArrHelper(root->left, arr, pos);
    arr[(*pos)++] = *root; // 拷贝整个节点结构
    BSTtoArrHelper(root->right, arr, pos);
}

void BSTtoArr(Tree* root, Tree arr[]) {
    int pos = 0;
    BSTtoArrHelper(root, arr, &pos);
}

对应的调用方式:

int nodeCount = TreeSize(root);
Tree* arr = (Tree*)malloc(nodeCount * sizeof(Tree));
BSTtoArr(root, arr);

// 业务逻辑使用数组...

free(arr);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:36:03