[英]Access violation reading location 0x00000000 in binary search tree
只显示二叉树的节点是什么样的。 我不确定有什么问题,但我觉得它与私有功能有关。 我如何比较私有数据,以便我可以看到我正在寻找的值是否在该节点内?
class binarytree
{
private:
class node
{
public:
int data;
node * left;
node * right;
node (int x)
{
data = x;
left=NULL;
right=NULL;
}
};
node * root;
这是我插入节点的方式
void insert(int x, node * &r)
{
if(r==NULL)
{
r= new node(x);
}
else
{
if(x < r->data)
{
//insert left
insert(x, r->left);
}
else
{
//insert right
insert(x, r->right);
}
}
}
以下是代码的一部分,当我尝试将x与r->数据进行比较时程序崩溃并给出错误消息“访问冲突读取位置0x00000000”时给我带来了麻烦
void remove(int x, node * &r)
{
if(x == r->data)
{
if(r->right == NULL && r->left == NULL)
{
r = NULL;
}
else if(r->right == NULL && r->left != NULL)
{
r = r->left;
}
else if(r->right != NULL && r->left == NULL)
{
r = r->right;
}
else
{
node * temp;
temp =r;
r = r->left;
while(r->right != NULL)
{
r = r->right;
}
r->right = temp->right;
delete temp;
}
}
else if ( x < r->data)
{
remove(x, r->left);
}
else if (x > r->data)
{
remove(x , r->left);
}
}
这是功能公开的地方。 然后我调用私有函数,以便我可以操作私有树。
public:
binarytree()
{
root = NULL;
}
~binarytree()
{
//tooo: write this
}
//return true if empty, false if not
bool empty()
{}
void insert(int x)
{
insert(x, root);
}
void remove(int x)
{
remove(x,root);
}
};
编辑:这是该程序的另一个功能,但可能导致r指向NULL。
int extractMin(node * &r)
{
if(r->left == NULL)
{
if(r->right == NULL)
{
return r->data;
}
else
{
int x = r->data;
r = r->right;
return x;
}
}
else
{
return extractMin(r->left);
}
}
这是检查r是否为NULL的新函数
void remove(int x, node * &r)
{
if(r == NULL)
{
cout<<"why am I null?"<<endl;
}
else
{
if(x == r->data)
{
if(r->right == NULL && r->left == NULL)
{
r = NULL;
}
else if(r->right == NULL && r->left != NULL)
{
r = r->left;
}
else if(r->right != NULL && r->left == NULL)
{
r = r->right;
}
else
{
node * temp;
temp =r;
r = r->left;
while(r->right != NULL)
{
r = r->right;
}
r->right = temp->right;
delete temp;
}
}
else if ( x < r->data)
{
remove(x, r->left);
}
else if (x > r->data)
{
remove(x , r->left);
}
}
}
在尝试访问内部成员之前,您应该始终检查NULL
:
void remove(int x, node * &r)
{
if(r != NULL)
{
// Your code
}
}
你调用以r
删除为NULL
然后尝试检查r.Left
。 然后在这里你有访问冲突
我也必须问,如果这对你有用吗? 特别insert
不会这样工作。 尝试
void insert(int x, node * &r)
{
if(r==NULL)
{
r= new node(x);
}
else
{
if(x < r->data)
{
if(r->left != NULL)
{
//insert left
insert(x, r->left);
}
else
{
r->left = new node(x);
}
}
else
{
if(r->right != NULL)
{
//insert right
insert(x, r->right);
}
else
{
r->left = new node(x);
}
}
}
}
好吧,错误说,当你试图解除引用时,r指向NULL。 所以你必须确保当你将memmory分配给r时它不会返回NULL。
binarytree()
{
root = NULL;
}
void remove(int x)
{
remove(x,root);
}
在您的情况下,您尝试解除引用NULL(如错误所示)当您在调用插入之前调用remove时,会在代码中发生这种情况。 你应该在删除开始时检查r是不是指向NULL。 或者甚至更好,确保在其NULL时不会解析r。
r
以某种方式为空。 您需要检查传入的r
是否为NULL
,或检查root
是否为非null,并且仅在子项存在时调用remove
。
您正在将x
与root
进行比较。 当您的树为空时, root == nullptr
。 您应首先检查是否r == nullptr
,如:
bool remove(int x, node * &r) {
if(!r) {
return false; // Indicate whether removal succeeded
}
//... etc.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.