首页 > 解决方案 > 二叉搜索树插入程序显示分段错误

问题描述

节点插入代码引发分段错误。当我尝试打印存储在根节点中的数据时,此代码会引发分段错误。

下面是二叉搜索树插入程序的实现。该程序使用递归插入给定节点。

#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;
}   

标签: cmallocbinary-search-treedynamic-memory-allocation

解决方案


问题是您没有将函数 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 )

推荐阅读