c - C - 二叉树的实现导致插入时出现奇怪的行为
问题描述
我有这样的二叉树设置:
`
我还像这样初始化 BT 的第一个节点:
`
到目前为止一切正常。但是,当我尝试插入我的 BT 时,我不断收到意外行为。我的插入函数看起来像这样。
`
但是,当我从 main 函数运行代码并尝试插入 BT 时,第一个节点显示得很好,但第二个节点变成了一个大而奇怪的数字。当我在调试器中运行它时,它会显示我期望的数字,但这不是打印出来的数字。这是我的主要方法。
`
问题出在我的插入函数中,但我不确定出了什么问题,因为当我通过调试器运行它时,我得到了预期值 5 和 6。
解决方案
在这些陈述中
struct Node* node1 = (struct Node*) malloc(sizeof(struct Node*));
^^^^^^^^^^^^
struct Node* node2 = (struct Node*) malloc(sizeof(struct Node*));
^^^^^^^^^^^^
您错误地分配了内存。而是写
struct Node* node1 = (struct Node*) malloc(sizeof(struct Node));
^^^^^^^^^^^
struct Node* node2 = (struct Node*) malloc(sizeof(struct Node));
^^^^^^^^^^^^
函数中也存在同样的问题insert
。
同样在函数内将return语句移动到函数的末尾
struct Node* insert(struct Node* rootPtr, struct Node* node) {
if (rootPtr == NULL) {
rootPtr = (struct Node*) malloc(sizeof(struct Node));
rootPtr->data = node->data;
rootPtr->left = NULL;
rootPtr->right = NULL;
}
if (rootPtr->data > node->data) {
rootPtr->left = insert(rootPtr->left, node);
} else if (rootPtr->data < node->data) {
rootPtr->right = insert(rootPtr->right, node);
}
return rootPtr;
}
请注意,将指向整个节点的指针作为第二个参数传递是低效且容易出错的。你可以只传递一个整数。所以函数应该声明为
struct Node* insert(struct Node* rootPtr, int data );
推荐阅读
- botframework - CardAction DisplayText 似乎不起作用
- corda - 将新节点添加到现有的 Corda 网络
- python - 将标准错误重定向到日志,要添加时间戳
- tensorflow - Tensorflow 图获取范围内的所有常量
- javascript - 弹出框 javascript+PHP 代码混合不起作用?
- python - 在 Python 中使用重复旋转多个列
- excel - SSIS 执行包失败
- reporting-services - 如何为 SSRS 中的所有报告订阅提供一个中心位置?
- c# - 我无法让我的精灵降落在我的平台之上
- python - 在 Django 设置中找不到使用 venv 安装的包