最近,我用 C++11 编写链表。使用这些概念,我尝试在 C++11 中编写树{一棵非常基本的树}实现代码。但它给我一个段错误。我在网上查了一下,发现它发生在程序尝试写入读取访问内存或尝试访问空闲内存时,但我无法弄清楚它是如何发生的。请帮助..
#include<iostream>
#include<cstdlib>
using namespace std;
struct node{
node *left;
node *right;
int key;
};
class tree{
public:
node *root;
tree(){
root->left=NULL;
root->right=NULL;
}
node *createnode(int data){
node *temp=new node;
temp->key=data;
temp->left=NULL;
temp->right=NULL;
return temp;
}
};
int main(){
tree t;
node *root;
root=t.createnode(1);
//root->left=t.createnode(2);
//root->right=t.createnode(3);
//root->left->left=t.createnode(9);
//root->left->right=t.createnode(7);
return 0;
}
最佳答案
t.root
未初始化,因此写入 root->left
和 root->right
在 tree
的构造函数调用未定义的行为。
现在,您的 tree
类并没有多大意义。它包含一个 root
节点指针,但您永远不会使用它。 createnode
可以只是一个自由函数或 node
的静态成员。更好的做法是完全封装节点,让 tree
有一个 insert
方法,该方法采用 int
,创建一个新节点,并将其插入到树中的适当位置。
关于c++ - 树实现给出段错误(核心转储)错误 c++ 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50028082/