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?