Deletion

There are several cases to be considered:
1.Deleting a leaf: Deleting a node with no children is easy, as we can simply remove it from the tree.



2.Deleting a node with one child: Delete it and replace it with its child.Here we have four cases.
Case 1:p is the left child of q with a left child
Case 2:p is the left child of q with a right child
Case 3:p is the right child of q with a left child
Case 4:p is the right child of q with a right child



3.Deleting a node with two children: Suppose the node to be deleted is called N. We replace the value of N with either its in-order successor (the left-most child of the right subtree) or the in-order predecessor (the right-most child of the left subtree).

Here is sample code for a destructive version of deletion
---------------------------------------------------
void DeleteNode(struct node * & node) {
if (node->left == NULL) {
struct node *temp = node;
node = node->right;
delete temp;
} else if (node->right == NULL) {
struct node *temp = node;
node = node->left;
delete temp;
} else {
// In-order predecessor (rightmost child of left subtree)
// Node has two children - get max of left subtree
struct node **temp = &node->left; // get left node of the original node
// find the rightmost child of the subtree of the left node
while ((*temp)->right != NULL) {
temp = &(*temp)->right;
}
// copy the value from the in-order predecessor to the original node
node->value = (*temp)->value;
// then delete the predecessor
DeleteNode(*temp);
}
}
----------------------------------------------------

Although this operation does not always traverse the tree down to a leaf, this is always a possibility; thus in the worst case it requires time proportional to the height of the tree. It does not require more even when the node has two children, since it still follows a single path and does not visit any node twice.