Deletion in binary search tree

后端 未结 3 480
既然无缘
既然无缘 2021-01-16 16:51

So when I delete in binary search tree, do I need to have like 7 different cases i.e.

  1. Left Leaf;
  2. Right Leaf;
  3. Left child with only left child.
3条回答
  •  醉酒成梦
    2021-01-16 17:16

    You can keep it a lot simpler than that, and simply restrict yourself to three cases when deleting a node from a BST (binary search tree) :

    1. a node without children (a leaf) : just remove it - nothing special needs to be done
    2. a node with one child : remove it, and move the child in its place
    3. a node with two children : swap it with either its in-order predecessor or successor, and then remove it

    The wiki page contains an example of how this could look in code.

    Or as a very basic example in C :

    if (current->left==NULL && current->right==NULL) {
        /* leaf node */
        bst_replace(current, NULL);
    }
    else if (current->left==NULL || current->right==NULL) {
        /* node with one child */
        bst_replace(current, ((current->left) ? current->left : current->right));
    }
    else {
        /* node with two children */
        Node* successor = bst_next(current);
        current->data = successor->data;
        bst_replace(successor, successor->right);
    }
    

提交回复
热议问题