[英]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.