So I’m trying to create my own BST for a spellchecker because I want to additional functionality (find nearby nodes for suggestions). Anyways, I can create the root node, but after that it doesn’t work. For example, if I have the following code:
BST myTree;
myTree.add("rootElement");
myTree.add("abcChild");
If I make root (node *root) public and check for myTree.root->left !=NULL || myTree.root->right != NULL, I get a seg fault. I don’t understand. Here’s some of my code:
struct node {
string data;
node *left;
node *right;
};
void BST::add(string newData)
{
//Find a position
if (root == NULL){
root = new node;
root->data = newData;
root->left = NULL;
root->right = NULL;
}
else{ //remember to include string
if(root->data.compare(newData) < 0){
// Add to left
addRecursive(root->left, newData);
}
else{
// Add to right
addRecursive(root->right, newData);
}
}
}
void BST::addRecursive(node *currentNode, string newData)
{
if (currentNode == NULL){
currentNode = new node;
currentNode->data = newData;
currentNode->left = NULL;
currentNode->right = NULL;
}
else{ //remember to include string
if(currentNode->data.compare(newData) < 0){
// Add to left
addRecursive(currentNode->left, newData);
}
else{
// Add to right
addRecursive(currentNode->right, newData);
}
}
}
What’s the deal?
In
add, when you dorootis a class variable, so that’s not a problem and is the correct way to do it. However, inaddRecursive, when you are doingcurrentNodeis a pointer that is passed by value to your function, so you are only making the local variablecurrentNodepoint to another place in memory. You need to pass the pointers by reference so that when you modify the parameter, it modifies the original instead of just the local variable. Just make the signature of your functionaddRecursivetovoid addRecursive(node*& currentNode, const string& newData). This will make the pointers be passed to the function by reference.Also notice that I changed
string newDatatoconst string& newData. That is so you avoid making a copy of the string in memory every time you call the function. You should make that change in all of your functions when you don’t need to modify a copy of the string passed to the function, to improve efficiency.