问题
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);
}
}
回答1:
What you're doing now in creating new nodes for the tree is that you're instantiating a temporary Node
object and then storing the address of that object. This is what &Node(k, i)
is doing.
The problem is that the temporary will go out of scope, and your BST now contains Node
pointers pointing to something that doesn't exist. That's more likely the reason your program stops with invalid address errors.
So instead of
&Node(k,i)
,
use
new Node(k, i)
.
This dynamically allocates a new Node
, making the pointer to this Node
"stick" and not be temporary.
Then of course, you're responsible for deallocating the memory for the BST when it's time to destroy the tree. That's when you need to go through the tree nodes and call delete
on each Node
.
来源:https://stackoverflow.com/questions/47237701/binary-search-tree-having-issues-with-insert-function