c - 二叉搜索树插入程序显示分段错误
问题描述
节点插入代码引发分段错误。当我尝试打印存储在根节点中的数据时,此代码会引发分段错误。
下面是二叉搜索树插入程序的实现。该程序使用递归插入给定节点。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *make (int);
struct node *insert (struct node *, int);
void
main ()
{
struct node *root;
root = NULL;
insert (root, 2);
insert (root, 3);
insert (root, 4);
insert (root, 5);
insert (root, 6);
insert (root, 7);
printf ("%d", root->data);
}
struct node *
make (int x)
{
struct node *temp;
temp = (struct node *) malloc (sizeof (struct node *));
temp->data = x;
temp->left = NULL;
temp->right = NULL;
return temp;
}
struct node *
insert (struct node *root, int x)
{
if (root == NULL)
{
root = make (x);
}
else
{
if (x <= root->data)
{
root->left = insert (root->left, x);
}
else if (x > root->data)
{
root->right = insert (root->right, x);
}
}
return root;
}
解决方案
问题是您没有将函数 insert 的返回值分配给节点根。
写
根 = 插入(根,2);
//...
另一个问题是您分配的内存不正确
temp = (struct node *) malloc (sizeof (struct node *));
^^^^^^^^^^^^^
必须有
temp = (struct node *) malloc (sizeof (struct node ));
^^^^^^^^^^^^^
同样在函数内插入内部 if 语句应该看起来像
if (x < root->data)
{
root->left = insert (root->left, x);
}
else
{
root->right = insert (root->right, x);
}
请注意,根据 C 标准,不带参数的函数 main 应声明为
int main( void )
推荐阅读
- sql - 获取当年每个月的订阅者计数,即使计数为 0
- python - 如何用pdfplumber完成for循环?
- bash - 如何使用 awk 将混合/部分缺失的记录提取到定义的顺序
- reactjs - 如何使用 ReactJS 更新由一组对象组成的堆肥状态?
- javascript - 这个功能只工作一次有什么原因吗?
- performance - 如何找出服务器可以在 Jmeter 中处理的每秒最大并发请求数
- android-jetpack-compose - DatePicker 文本值更新到前一天而不是选择日期
- rust - Rust axum / hyper 请求局部变量
- excel - Excel Pivot 值作为列标签
- pine-script - 在 pine 脚本中逐条满足某些条件