I'm using recursive functions to insert a node into my binary search tree. The program works by creating a root node if there is none. Root is a pointer to a node struct. If the root already exists I call the worker function.
Note: Key is int and Item is a string.
When calling the worker function, current->key(-858993460) and current->item(Error reading characters of string) are not their expected values (1, "Harrold").
Recursion continues until this Exception occurs:
"Exception thrown: read access violation. current was 0xCCCCCCCC."
Key k and Item i are their expected value. It is only why I'm trying to access them from Node* root that they change and I'm unsure why this is happening.
Any help is appreciated
void BST::insert(Key k, Item i)
{
if (root == nullptr) {
root = &Node(k, i);
}
else insertRec(k, i, root);
}
void BST::insertRec(Key k, Item i, Node* current)
{
if (current->key == k)//if the key of the inserted node is = to an existing key, change the item.
{
current->item = i;
}
else if (current->key > k)//if the key of the current node is larger than key inserted traverse leftchild recursively calling function
{
if (current->leftChild != nullptr)
insertRec(k, i, current->leftChild);
else
current->leftChild = &Node(k, i);
}
else if (current->key < k)
{
if (current->rightChild != nullptr)
insertRec(k, i, current->rightChild);
else
current->rightChild = &Node(k, i);
}
}
current->leftChild = &Node(k, i);-- Explain what this weird looking line does. What's the reason for storing a pointer to a temporary (which is doomed for failure)? Second, please post a minimal reproducible example - PaulMcKenzienewin C++, or better yetstd::unique_ptr<>andmake_unique? If not, then your entire existing BST is not built correctly, way before theinsertis called. - PaulMcKenzie