构建二叉搜索树时的分段错误

Segmentation fault while building binary search tree

本文关键字:分段 错误 搜索树 构建      更新时间:2023-10-16

我正在构建一个二叉搜索树,但该函数给出了分割错误。我不知道问题出在哪里。

树没有构建insertintree中的部分无法正常工作,我已经尝试了方法,但它不起作用

#include<bits/stdc++.h>
using namespace std;
struct node // structure of node
{
int k;
node* left = NULL;
node* right = NULL;
};    
void insertintree(node* root, int key)
{
if (root == NULL)//root addition
{
node* root = new node;
root->k = key;
}
else 
{
if (root->k < key)  insertintree(root->right, key);
else insertintree(root->left, key);
}
}    
void inorder(node* root) 
{
if (root != NULL) 
{
inorder(root->left);
cout << root->k;
inorder(root->right);
}
}    
int main() 
{
node* root = NULL;
insertintree(root, 1);
cout << root->k;
}

您主要有两个问题:

  1. 您需要通过引用传递root,否则insertintree将与您传递的root的副本一起使用。

    void insertintree(node* &root, int key)
    //                     ^^^
    {
    }
    
  2. 其次,在你的第一if身上,你重新宣布了新的rootNode将遮蔽通过的那个。更改为

    if (root == NULL)//root addition    
    {
    root = new node;
    root->k = key;
    }
    

还要避免与#include<bits/stdc++.h>using namespace std;一起练习:为什么?请参阅以下讨论:

  • 为什么我不应该 #include ?
  • 为什么是"使用命名空间 std;"被认为是不良做法?

您的代码存在多个问题。首先是你重新声明root.

void insertintree(node* root,int key) // root declared here
{
if(root==NULL)
{
node* root = new node; // root redeclared here

这是两个不同的变量(即使它们具有相同的名称)。你应该写这个

void insertintree(node* root, int key) // root declared once
{
if(root==NULL)
{
root = new node; // now this is the root declared above

第二个问题是,您希望intsertintree函数更改main中声明的根,但事实并非如此。同样,仅仅因为两个变量具有相同的名称并不意味着它们是相同的变量。

void insertintree(node* root,int key) // a variable called root
{
...
}
int main()
{
node* root = NULL; // another variable called root
...
}

insertintree中更改root变量对main中称为root的变量完全没有影响,它们是不同的变量。

要完成这项工作,您必须通过引用传递。当变量是引用时,对它的更改会更改被引用的变量。像这样更改insertintree函数

void insertintree(node*& root,int key)
// ^ this makes root a reference
{

现在root是对main中变量的引用,对它的更改也将更改main中的变量。

同样,当你像这样递归地调用insertintree

insertintree(root->right,key);

insertintree函数将能够更改root->right,因为它需要引用root->right