c - 创建二叉树的指针问题

标签 c pointers binary-tree

我正在用 c 中的位串创建二叉树。即 1100100 创建一棵树:

  1
 / \
1   1

我决定使用递归函数来构建这棵树,但是我一直收到错误 调试断言失败... 表达式:CrtIsValidHeapPointer(pUserData)

这是我的代码片段

typedef
struct Node {
  char key;
  struct Node *left;
  struct Node *right; 
} Node;

char string[1000];
int i = 0;

void insertRecursivePreorder(Node **node)
{
    Node* parent = *node;
    if(string[i] == '0')
    {
        parent = NULL;
        i++;
    }
    else
    {
        Node *newn = (Node*)malloc(sizeof(Node));
        newn->key = string[i];
        parent = newn;
        i++;
        insertRecursivePreorder(&newn->left); //errors occur here
        insertRecursivePreorder(&newn->right); //errors occur here
        free(newn);
        free(parent);
    }
}

int main(void)
{
    void printTree(Node* node);
    Node* root = NULL;
    scanf("%s", string);
    insertRecursivePreorder(&root);
    //... do other junk
}

我想知道为什么会出现此错误以及我可以做些什么来解决它。

最佳答案

眼前的问题很可能是对指针调用 free 两次。在 insertRecursivePreorder 中,您将 parent 设置为 newn,然后在两者上调用 free。例如,以下程序失败(但如果您注释掉其中一个 free(..) 则可以运行):

#include <stdlib.h>
int main() {
  int *a = malloc(sizeof(int)),
      *b = a;
  free(a);
  free(b);
  return 0;
}

但是,您的逻辑存在几个问题。您应该只在完全 完成指针的操作后才调用free,因此如果您稍后要使用您的树,您将无法在构建它时释放它。您应该创建第二个函数 recursiveDestroyTree,它遍历并调用树上的 free(自下而上!)。

而且,您可能需要 *node = newn 而不是 parent = newn,因为后者是唯一实际修改 node 的.

(您也可以更改您的函数以返回一个 Node * 指针,然后就可以了:

root = insertRecursivePreorder();

newn->left = insertRecursivePreorder();
newn->right = insertRecursivePreorder();

而不是试图跟踪指向指针等的指针)

(此外,在风格上,使用全局变量通常是不好的做法,因此您可以让您的 insertRecursivePreorder 采用 int ichar * string 参数并使用它们代替全局变量。)

关于c - 创建二叉树的指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10360031/

相关文章:

c - 段错误 - 处理堆栈数据结构

c - C 中的 SQLite 绑定(bind) blob 提前终止

c - C中的段错误,无法找出原因

在C中将两个int数组复制到一个char*

algorithm - 合并两个二叉树节点和

algorithm - 最小化二叉搜索树的高度

C++ 父类(super class)数组还访问子类方法?

c - 生产者消费者问题中的竞争条件

c - If 语句不适用于 C 中的 char 数组元素

c - 创建链表时不需要创建实际节点吗?