gpt4 book ai didi

c++ - 段错误(核心已转储)- 线程二进制搜索树

转载 作者:搜寻专家 更新时间:2023-10-31 00:51:38 25 4
gpt4 key购买 nike

我不断收到以下错误:段错误(核心已转储)。我找出了导致问题的代码行(在程序中标有注释)。请告诉我为什么会发生此错误以及如何解决。

我尝试试运行我的代码(在纸上),没有发现任何逻辑错误(根据我的理解)。
我最近才开始接触编码和 stackoverflow,请指导我如何进一步改进我的问题以及我的代码。谢谢!

class tree
{
struct node // Creates a node for a tree
{
int data;
bool rbit,lbit; // rbit/lbit= defines if right/left child of root is present or not
node *left,*right;
};
public:
node *head,*root;
tree() // constructor initializes root and head
{
root=NULL;
head=createnode(10000);
}
node *createnode(int value)
{// Allocates memory for a node then initializes node with given value and returns that node
node *temp=new node ;
temp->data=value;
temp->lbit=0;
temp->rbit=0;
temp->left=NULL;
temp->right=NULL;
return temp;
}
void insert(node *temp,int value) // Creates binary search tree node by node
{
if(root==NULL) // Checking if tree is empty
{
root=createnode(value); //Root now points to new memory location
head->left=root;
head->lbit=1;
root->left=head;//this line gives the segmentation fault (what i thought before correction)
}

}
void inorder(node *root) // Inorder traversal of tree (this function is logically incorrect)
{
if(root==NULL)
return;
inorder(root->left);
cout<<root->data<<"\t";
inorder(root->right);
}
void getdata()//Accepts data , creates a node through insert() , displays result through inorder()
{
int data;
cout<<"Enter data"<<endl;
cin>>data;
insert(root,data);
inorder(root);
}
/*void inorder(node *root) // Working inorder code
{
if(root->lbit==1)
inorder(root->left);
cout<<root->data<<"\t";
if(root->rbit==1)
inorder(root->right);
}*/
};
int main()
{

tree t; // Tree Object
t.getdata(); // Calling getdata
return 0;
}

最佳答案

我认为评论部分在很大程度上反射(reflect)了沟通不畅。很容易相信您正在那条特定线路上遇到崩溃。

实际情况并非如此。相反,您所做的是在您的树中创建一个循环,该循环导致 inorder 函数无限递归。这会导致出现段错误的堆栈溢出——如果您只是在附加调试器(例如 gdb)的情况下运行程序,这将非常容易发现。

temp = createnode(value);
if(root == NULL)
{
root = temp;
head->left = root;
head->lbit = 1;
temp->left = head;
}

查看您刚刚创建的循环:

head->left points to root
root->left == temp->left, which points to head

中序遍历现在将访问:

root
head
root
head
root
head
...

因为它永远不会到达左分支的末尾,所以该函数在堆栈溢出和崩溃之前不会输出任何内容。

所以不,您的代码在逻辑上不正确。它有一个基本的设计缺陷。您需要重新考虑在树中存储的内容以及原因。

关于c++ - 段错误(核心已转储)- 线程二进制搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54452487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com