简体   繁体   中英

How do I delete a node from a binary search tree

How do I implement a function to delete a node from a binary search tree? Below is my current function:

    void makeDeletion(TreeNode *&tree) {
    TreeNode *NodeToDelete;
    NodeToDelete = tree;
    TreeNode *InOrder;

    if (tree->right == NULL && tree->left == NULL) {
        delete NodeToDelete;
    }
    if (tree->right == NULL) {
        tree = tree->left;
        delete NodeToDelete;
    }
    else if (tree->left == NULL) {
        tree = tree->right;
        delete NodeToDelete;
    }
    else {
        InOrder = tree->right;
        while (InOrder->left != NULL) {
            InOrder = InOrder->left; 
        }

        NodeToDelete->value = InOrder->value;
        remove(InOrder, InOrder->value);
    }
}

And here is the remove function I have that locates the value to be deleted:

    void remove(TreeNode *&tree, ANY num) {//Removed Need for ">"
    if (tree == NULL){
        return;
    }

    if (tree->value == num) {
        makeDeletion(tree);
    } else if (num < tree->value) {
        remove(tree->left, num);
    } else {
        remove(tree->right, num);
    }
};//Remove

As it stands I feel like I'm very close, but when I go to output the contents of the binary tree the program crashes. I am trying to use an approach where, if the node has two children, I locate the in order successor, swap the values of the nodes of the in order successor and the node to be "deleted," and then delete the in order successor. Without adjusting the remove function, what bit of information am I missing to make the makeDeletion function work as described?

EDIT: in the makeDeletion function I mistakenly wrote two if statements in succession. The second if statement should be an else if statement.

In makeDeletion , if tree is a leaf (both left and right are NULL ), you delete the leaf node, and don't set tree = nullptr . This leaves a dangling reference in your tree to memory that has been freed. Also, you then dereference the (now deleted) node in the next if . Either one of these can result in your crash.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM