Tran Hoai Nam
Tran Hoai Nam

Reputation: 1363

Delete the only node from a BST

My BST have only ONE node. I wrote a code to delete that node but it's still there. Just like it hasn't been... updated. Here is my simple code, just to test the case

void Delete(BSTree* tree, int& key)
{
    if (key == tree->key)
        tree=NULL;
}

And my BSTree class doesn't have a parrent part. Just the value and the left and right pointer. What is wrong with my code? Thank you!

Upvotes: 0

Views: 84

Answers (1)

pickypg
pickypg

Reputation: 22332

You aren't changing the actual tree pointer. You're only changing the pointer that was allocated on the stack, pointing to the same address as the passed-in pointer.

You want BSTree *&tree so that you get the reference to the original pointer, so that any changes effect it.

As Als points out, don't forget to free memory in addition to the above.

Upvotes: 1

Related Questions