我正在尝试向bst插入值,但是当我在插入之前检查root是否为NULL时,我得到了一个段错误。如何首先将树初始化为NULL或我做错了什么?
void StdClass::add(int val, ...){
Node *temp, *parent;
if (root == NULL) {//throws segfault here..
root = new Node(...);
root->left = NULL;
root->right = NULL;
temp = root;
return;
} else {
temp=root;
while (temp!=NULL) {
if (val <= temp->key){
parent = temp;
temp=temp->left;
//root =temp;
return;
} else {
parent =temp;
temp=temp->right;
//root=temp;
return;
}
}
Node *newNode = new Node(...);
newNode->left = NULL;
newNode->right = NULL;
//Now insert the new node BELOW parent
if(val <= parent->key){
parent->left = newNode;}
else{
parent->right = newNode;
}
}
}
root是在StdClass中私有定义的。
struct Node{
int key;
std:string b;
std::string c;
Node *parent;
Node *left;
Node *right;
Node(){};
Node(int val, std::string s, std::string t){
key = val;
b= s;
c = t;
}
}
Class StdClass{
public:
void add(int, std::string, std::string);
private:
Node *root;
}
从另一个函数调用它..
void StdClass::test(){
int x = 0;
while(x < 10){
add(x,"test","test");
x++;
}
}
的main.cpp
#include "StdClass.h"
int main(){
StdClass s;
s.test();
return 0;
}