构建二叉搜索树时的分段错误
Segmentation fault while building binary search tree
我正在构建一个二叉搜索树,但该函数给出了分割错误。我不知道问题出在哪里。
树没有构建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;
}
您主要有两个问题:
-
您需要通过引用传递
root
,否则insertintree
将与您传递的root
的副本一起使用。void insertintree(node* &root, int key) // ^^^ { }
-
其次,在你的第一
if
身上,你重新宣布了新的root
Node
将遮蔽通过的那个。更改为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
。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?