So I built a BST based off of the example in class. My peers' trees all work fine, however, I am getting a segmentation fault when I add a second element. I have isolated the error coming from this line - 'if(current->left == NULL){' I am not sure why it is resulting in a segmentation fault and how to avoid it. I will leave the related insertNode code as well as the Node class as I feel it might be a problem there.
template <class T>
void BST<T>::insertNode(T value){
TreeNode<T> *node = new TreeNode<T>(value);
if(isEmpty()){
cout << "Is root" << endl;
root = node;
}else{
cout << "Is not root" << endl;
TreeNode<T> *parent = NULL;
TreeNode<T> *current = root;
cout << "Starting Loop" << endl;
while(true){
parent = current;
if(value < current->key){
cout << "less tahn" << endl;
//Left
current = current->left;
cout <<"left" << endl;
if(current == NULL){
//we found our location/insertion point
cout << "Found Spot" << endl;
parent->left = node;
break;
}
cout << "Not NULL" << endl;
}
else {
//Right
cout << "Right" << endl;
current = current->right;
if(current == NULL){
//we found our location/insertion point
cout << "Found Spot" << endl;
parent->right = node;
break;
}
}
}
}
}
And the treeNode class -
template <class T>
class TreeNode{
public:
TreeNode();
TreeNode(T k);
~TreeNode();
T key;
TreeNode *left;
TreeNode *right;
};
template <class T>
TreeNode<T>::TreeNode(){
left = NULL;
right = NULL;
}
template <class T>
TreeNode<T>::TreeNode(T k){
left = NULL;
right = NULL;
key = k;
}
current->left == NULL
you should check ifcurrent == NULL
– SHR