0
votes

I have implemented a Binary Search tree in C++.

For the delete method, everything works except for the last case, when the only tree is the parent and it points to two null children. Now the problem is: I wish to print out what the left and right subtrees to the parent equal to after I have deleted the subtree. They both as well as the parent should be NULL but when I try to output these values I get a STATUS_ACCESS _VIOLATION.

Here is the code for delete in question. I wish to delete the parent node, and set the tree->left = tree->right = NULL.

void BST_delete(string key, BST & tree) { 
    if ((!BST_has(key, tree) || BST_isEmpty(tree))) {
        return;
    } else if (tree->key == key) {
        if (tree->right == NULL && tree->left == NULL) {
            tree = NULL;                      // <-- THIS IS IN QUESTION
        } else if (tree->left == NULL) {
        ...
            } ....
}

MAIN:

int main() {
    BST bst;
    BST_init(bst);
    BST_insert("a",bst);
    BST_print(bst);
    cout << endl;

    BST_delete("a",bst);
    BST_print(bst); // <-- doesnt print anything (which is right)
    cout << bst->right; //<-- Gives me error
    return 0;
}
2
Have you tried using a debugger? - Jonathon Reinhart
OT: You should think about implementing these functions as members of BST. - wonce
@wonce, That's currently being remedied, actually, at least if some evidence of mine has led me to the correct conclusion. - chris
I don't understand in you MAIN, you have deleted bst in BST_delete(bst = NULL), why do you still want to do bst->right? - A Lan

2 Answers

0
votes

You can check for NULL (or nullptr):

voit printNode(BSTNode* p) {
     cout << ( p==NULL ? "null" : *p);
}

if (bst != NULL) {
     cout << printNode(bst->right);
     cout << printNode(bst->left);
}

and add this check to the BST_print function.

0
votes

This is what's happening:

BST_delete("a",bst);
// bst is NULL
BST_print(bst); // equivalent to BST_print(NULL)
cout << bst->right; // Gives an error, because you 
                    // can't access a member on a pointer that is NULL

The last line is like saying NULL->right, which doesn't make sense.

I'm not sure what to tell you to fix it - as a commenter points out, why would you still want to call bst->right after you've deleted bst? Perhaps it is best to either delete that line, or do:

if (bst != NULL) cout << bst->right