简体   繁体   中英

Binary Search Tree deletion of target node has two children

Here is my code, the replacement was correct (replaced the target node with the largest node in the left sub-tree), but after the replacement, both of the left and right sub-trees are gone.

Here is my code:

else if (temp->left != NULL && temp->right != NULL)
    {
        minLeaf = temp->left;
        minLeafMa = temp->left;
        parentRight = parent->right;

        while (minLeaf->right != NULL)
        {
            minLeafMa = minLeaf;
            minLeaf = minLeaf->right;
        }
        if (parent->left == temp)
        {
            parent->left = minLeaf;
            minLeafMa->right = NULL;
        }
        else if (parent->right == temp)
        {
            parent->right = minLeaf;
            minLeafMa->right = NULL;
        }
    }

The correct way of deleting a node x with 2 children is finding the inorder successor or predecessor of x , replacing x 's value with the predecessor 's or successor 's values and call delete on either of them(whichever you used).

You are using the predecessor here. You are doing

parent->left = minLeaf;

which points the left of parent to the leaf node(the predecessor node) resulting in all the nodes in between to be gone. Instead what you should do is

temp->data = minLeaf->data;

and recursively call delete on minLeaf .

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