I am trying to build a basic Binary search tree in C++ and running into some problems, specifically when I try to insert a node via function and read, it gives me segmentation fault. But the same node struct works perfectly fine when I manually insert it. The code for BST insert is as follows, and is most likely the culprit:
void BST::insert(Node* temproot,int val){
// std::cout << root->value <<std::endl;
if(!temproot){
Node* newNode = new Node;
newNode->value = val;
temproot = newNode;
std::cout << "Added Node with Value: " << val << std::endl;
return;
}
if(val<(temproot->value)){
std::cout << "LEFT" << std::endl;
insert(temproot->left, val);
}else{
std::cout << "RIGHT" << std::endl;
insert(temproot->right, val);
}
}
The node structure looks like this:
struct Node{
int value;
Node* left = nullptr, *right = nullptr;
};
And the BST class looks something like below:
class BST{
public:
Node* root= new Node;
BST(int val){
root->value = val;
}
void insert(Node*,int val);
void insertStart(int vasl){
Node* temproot = root;
insert(temproot, vasl);
}
void print(Node*);
void _print(){
print(root);
}
};
When I try to print it as follow, it gives me segmentation fault:
void BST::print(Node* temp){
std::cout << temp->value << std::endl;
temp = temp->left;
std::cout << (temp->value) << std::endl;
}
I am a bit new to C++ and am having struggle pin pointing it for couple of days. Can someone help me figure out what I am doing wrong here?