Course contentsShow
← C
Lesson 1029 of 1,21914. Data Structures in CFree lesson

The three cases of node deletion

The three cases of node deletion

What you'll learn: How to maintain the integrity of a Binary Search Tree (BST) when removing nodes with different numbers of children.

Deleting a node from a BST isn't as simple as just "erasing" it. Because the tree follows a specific order—where left is smaller and right is larger—we must ensure the remaining nodes stay connected correctly. There are three distinct scenarios we have to handle.

Case 1: The Leaf Node (No Children)

This is the easiest scenario. Think of it like pruning a dead leaf off a branch. Since the node has no children, you can simply remove it and set its parent’s pointer to NULL. No other part of the tree is affected.

Case 2: One Child

If the node you want to delete has one child (either left or right), think of it like a middle manager resigning. To keep the company running, the manager’s boss simply connects directly to the manager’s assistant. You "bypass" the deleted node by linking its parent directly to its only child.

Case 3: Two Children

This is the complex case. You can't just delete a node with two children because you'd leave two "drifting" subtrees. Instead, you must find a replacement.

To keep the tree in order, you look for the Inorder Successor—the smallest value in the right subtree. You swap the value of the node you want to delete with this successor's value. Because the successor is the smallest on the right, it is guaranteed to have at most one child. You then delete the successor using Case 1 or Case 2.

How it looks in logic

struct Node* deleteNode(struct Node* root, int key) {
    if (root == NULL) return root;

    // 1. Find the node to delete
    if (key < root->data) root->left = deleteNode(root->left, key);
    else if (key > root->data) root->right = deleteNode(root->right, key);
    else {
        // 2. We found it! Handle the cases:
        
        // Case 1 & 2: Zero or One Child
        if (root->left == NULL) {
            struct Node* temp = root->right;
            free(root);
            return temp;
        } else if (root->right == NULL) {
            struct Node* temp = root->left;
            free(root);
            return temp;
        }

        // Case 3: Two Children
        struct Node* temp = findMin(root->right); // Find successor
        root->data = temp->data; // Copy successor's value to this node
        root->right = deleteNode(root->right, temp->data); // Delete successor
    }
    return root;
}

Key takeaway

Deletion ranges from simple removal (leaf) to a bypass (one child), to a value-swap with the smallest node in the right subtree (two children).