[英]binary search tree insert function c++
I have the following problem. 我有以下问题。 I was coding in C++ 2 years ago and now decided to practice this language.
2年前,我使用C ++进行编码,现在决定练习这种语言。 I don't know what is going on, because compiler says it is an access viloation when I want to access root->data after insertion.
我不知道发生了什么,因为编译器说插入后要访问root-> data时这是访问冲突。 May be I completely forgot programming concepts with memory allocation or etc, but help me please I can't see a mistake here!
可能是我完全忘记了内存分配等编程概念,但请帮助我,我看不到这里的错误! Thanks in advance!
提前致谢!
#define BLACK 0
#define RED 1
using namespace std;
struct Node {
Node* left, *right;
int data;
bool color;
Node(int key) {
data = key;
left = right = NULL;
color = RED;
}
};
struct RBTree {
Node* root;
RBTree() { root = NULL; }
void insertBST(Node* node, int key) {
if (node == NULL) {
node = new Node(key);
}
else {
if (key < node->data) {
insertBST(node->left, key);
}
else {
insertBST(node->right, key);
}
}
}
void insert(int key) {
insertBST(root, key);
}
};
int main()
{
RBTree tree;
tree.insert(10);
cout << tree.root->data;
_getch();
return 0;
}
Try this: 尝试这个:
struct RBTree {
Node* root;
RBTree() { root = NULL; }
void insertBST(Node** node, int key) {
if (*node == NULL) {
*node = new Node(key);
}
else {
if (key < (*node)->data) {
insertBST(&(*node)->left, key);
}
else {
insertBST(&(*node)->right, key);
}
}
}
void insert(int key) {
insertBST(&root, key);
}
};
if (node == NULL) {
node = new Node(key);
}
In the above code segment you are creating a new node when the root == NULL. 在上面的代码段中,当根== NULL时,您将创建一个新节点。 But you are not assigning the newly created node to the root.
但是您没有将新创建的节点分配给根。 Need to pass by reference as follow.
需要通过引用如下。
T obj;
if ( !ptr )
ptr = &obj;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.