[英]Error when working with pointers in insertion of a node in a binary search tree
所以我有以下代碼:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Node
{
int value;
Node *left = NULL;
Node *right = NULL;
Node(int value)
{
this->value = value;
}
};
struct BST
{
Node *root = NULL;
void insert(int value)
{
cout<<"Inserting: "<<value<<endl;
Node *current = root;
while(current != NULL)
{
cout<<"YEA";
if(value > current->value)
{
current = current->right;
}
else current = current->left;
}
current = new Node(value);
cout<<"In the node val: "<<current->value<<endl;
if(root == NULL)
{
cout<<"Root is NULL but it shouldn't\n";
}
cout<<"Root val: "<<root->value<<endl;
}
void remove(int value)
{
Node *toReplace = NULL;
Node *toBeReplacedWith = NULL;
toReplace = search(value);
Node *current = toReplace->left;
if(current == NULL) toBeReplacedWith = toReplace->right;
else
{
while(current->right != NULL)
{
current = current->right;
}
toBeReplacedWith = current;
}
current->value = toBeReplacedWith->value;
current->left = toBeReplacedWith->left;
current->right = toBeReplacedWith->right;
free(toBeReplacedWith);
}
Node* search(int value)
{
Node *current = root;
while(current != NULL && current->value != value)
{
if(current->value > value) current = current->left;
else current = current->right;
}
if(current == NULL)
{
cout<<"The node didn't exist in the BST";
}
return current;
}
void traverse()
{
rec_traverse(root);
}
private:
void rec_traverse(Node * current)
{
if(current == NULL) return;
rec_traverse(current->left);
cout<<current->value<<endl;
rec_traverse(current->right);
}
};
int main()
{
BST tree;
for(int i = 0; i < 10; ++i)
{
tree.insert(i);
}
tree.traverse();
return 0;
}
有人可以告訴我為什么插入元素時根仍然指向NULL而不是Node實例嗎? 我什至檢查當前指針是否有值,並且具有,但由於某種原因,當根應該為第一個分配值的節點時,根為NULL
有人可以告訴我為什么插入元素時根仍然指向NULL
您的函數BST::insert(int value)
絕對不會修改root
。
這就是為什么root
保持NULL的原因。
使您的方法起作用的一種方法是讓current
指向要修改的指針 ,而不是讓current
持有該指針的副本 。
您正在更改current
所指向的Node*
,但永遠不要觸摸根。
current = new Node(value);
應該是root = new Node(value);
如果root
為null。
此外,除了這里的問題外,如果您使用遞歸調用進行插入和刪除,則代碼將更簡單(並且您不必擔心root
指向null的情況,因為它會隱式處理)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.