My code seems like it should be working given the algorithm, but I'm new to C++ and it seems that these pointers are overwriting themselves when I call insert multiple times. For example, if I call insert with values 1, 3, 5, then the root will be 1 (as expected), but 3 will be overwritten and the right child of the root will have value 5 instead of 3.
virtual bool insert(const Data& item) {
if(root == NULL){
BSTNode<Data> newNode (item);
root = &newNode;
isize++;
return true;
}
BSTNode<Data>* nextNode = root;
BSTNode<Data>* prevNode = NULL;
bool isLeft;
while(nextNode!=NULL) {
if (item < nextNode->data) {
prevNode = nextNode;
nextNode = nextNode->left;
//std::cout << prevNode->data;
isLeft = true;
}
else {
prevNode = nextNode;
nextNode = nextNode->right;
//std::cout << prevNode->data;
isLeft = false;
}
}
BSTNode<Data> createNode (item);
createNode.parent = prevNode;
if (isLeft) prevNode->left = &createNode;
else prevNode->right = &createNode;
isize++;
return true;
}
You have an invalid pointer due to pointing to a local object which is going to destroy:
BSTNode<Data> newNode (item);
root = &newNode;
Object newNode
is a local object within method insert
after returning from this method (it goes out of scope), pointer root
will point to a destroyed object. A naive possibility to solve the problem is allocating newNode
in heap by new
:
root = new BSTNode<Data>(item);
but you must delete
it somewhere, and also same issue for createNode
.
As recommended by many, you should use smart-points such as unique_ptr
and shared_ptr
.
Assuming that root
is a member variable, you need to allocate it on the heap and not on the stack:
if(root == NULL){
root = new BSTNode<Data>(item);
isize++;
return true;
}
Otherwise the node is destroyed once it goes out of scope at the closing brace of the if
body. The same goes for
if (isLeft) prevNode->left = new BSTNode<Data>(item);
else prevNode->right = new BSTNode<Data>(item);
I haven't checked your actual insertion logic though. You should should post the entire code, there is too little here to check it. Is it a binary tree?
Edit: Don't forget to delete the nodes if you create them on the heap, as per MM's answer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.