Hi all,
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 object. 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.
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;
}
elseif (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);
}
elseif (current->key < k)
{
if (current->rightChild != nullptr)
insertRec(k, i, current->rightChild);
else
current->rightChild = &Node(k, i);
}
}