allizwell.jobsdoor360.in

Insertion and Deletion

Data Structures and Algorithms / Trees and Binary Search Trees / Insertion and Deletion in BST

Insertion and Deletion in Binary Search Tree (BST)

Insertion and deletion are two important operations in a Binary Search Tree (BST). Insertion adds a new value while maintaining the BST ordering property. Deletion removes an existing node without breaking that property. In this lesson, we will understand all insertion and deletion cases step by step, including deleting a leaf node, a node with one child, and a node with two children. We will also learn recursive C++ implementations, dry runs, and complexity analysis.

1. What Is Insertion in a BST?

Insertion means adding a new node to a Binary Search Tree. The new node must be placed at the correct position so that the BST property remains valid.

Remember the BST property:

  • Values smaller than a node are placed in its left subtree.
  • Values greater than a node are placed in its right subtree.
  • Both subtrees must also follow the same rule.

Example

Consider the following BST:

          50
         /  \
       30    70
      / \    / \
     20 40  60 80

Suppose we want to insert 35. We compare it with the root and move through the tree until we find an empty position.

2. Algorithm for Insertion

  1. Start from the root node.
  2. If the root is NULL, create a new node and return it.
  3. If the new value is smaller than the current node, move left.
  4. If the new value is greater than the current node, move right.
  5. Continue until an empty position is found.
  6. Insert the new node at that position.
In this lesson, we use a distinct-key BST policy: duplicate values are ignored. Other implementations may choose a different consistent duplicate-handling policy.

3. Dry Run: Inserting a New Node

Consider this BST:

          50
         /  \
       30    70
      / \    / \
     20 40  60 80

We want to insert 35.

Step 1: Compare with 50

35 is smaller than 50, so move to the left child.

Step 2: Compare with 30

35 is greater than 30, so move to the right child.

Step 3: Compare with 40

35 is smaller than 40, so move to the left child.

Step 4: Find an Empty Position

The left child of 40 is NULL. Insert 35 there.

             50
            /  \
          30    70
         / \    / \
        20 40  60 80
           /
          35

Insertion Result: 35 inserted successfully

4. C++ Program for Insertion in BST

We use recursion to find the correct position and insert the new node.

#include <iostream>
using namespace std;

struct Node {

    int data;
    Node* left;
    Node* right;

    Node(int value) {

        data = value;
        left = nullptr;
        right = nullptr;
    }
};

Node* insert(Node* root, int value) {

    // If position is empty, create a new node
    if (root == nullptr) {
        return new Node(value);
    }

    // Move to the left subtree
    if (value < root->data) {
        root->left = insert(root->left, value);
    }

    // Move to the right subtree
    else if (value > root->data) {
        root->right = insert(root->right, value);
    }

    // Equal values are ignored in this implementation
    return root;
}

void inorder(Node* root) {

    if (root == nullptr) {
        return;
    }

    inorder(root->left);

    cout << root->data << " ";

    inorder(root->right);
}

int main() {

    Node* root = nullptr;

    root = insert(root, 50);
    root = insert(root, 30);
    root = insert(root, 70);
    root = insert(root, 20);
    root = insert(root, 40);
    root = insert(root, 60);
    root = insert(root, 80);

    root = insert(root, 35);

    cout << "Inorder Traversal: ";

    inorder(root);

    return 0;
}

Output

Inorder Traversal: 20 30 35 40 50 60 70 80

5. What Is Deletion in a BST?

Deletion means removing a node from a Binary Search Tree. The main challenge is to remove the node while preserving the BST property.

Unlike insertion, deletion has three different cases depending on the number of children of the node being removed.

6. Three Cases of Deletion in BST

Case 1: Deleting a Leaf Node

A leaf node is a node that has no children. It can be removed directly by replacing its parent's corresponding child pointer with NULL.

Consider this BST:

          50
         /  \
       30    70
      / \    / \
     20 40  60 80

Delete node 20.

Since 20 has no children, simply remove it.

          50
         /  \
       30    70
        \    / \
        40  60 80
Leaf-node deletion is the simplest case because no child needs to be connected to another node.

Case 2: Deleting a Node with One Child

If a node has exactly one child, replace the node with its only child.

Consider this BST:

          50
         /  \
       30    70
         \
          40

Delete node 30.

Node 30 has only one child, which is 40. Connect 40 directly to 50.

          50
         /  \
        40   70

The same rule applies if the node has only a left child.

Case 3: Deleting a Node with Two Children

This is the most important deletion case. When a node has two children, we cannot simply remove it because both subtrees must remain connected correctly.

A common solution is to replace the node's value with its inorder successor and then delete the successor from its original position.

What Is an Inorder Successor?

The inorder successor of a node is the next greater value in inorder traversal. For a node that has a right subtree, its inorder successor is the smallest value in that right subtree.

Consider this BST:

              50
             /  \
           30    70
          / \    / \
        20  40  60  80

We want to delete 50. Its right subtree contains 60, 70, and 80. The smallest value in that subtree is 60.

Therefore:

  1. Find the inorder successor, which is 60.
  2. Replace 50 with 60.
  3. Delete the original node containing 60.
              60
             /  \
           30    70
          / \      \
        20  40      80

Deleted Value: 50

Replacement Value: 60

The inorder successor has no left child. It may have a right child, so that right child must be reconnected when the successor is removed.

7. Finding the Minimum Value in a BST

To find the inorder successor, we first need a function that finds the minimum node in a subtree.

The minimum value is located at the leftmost node.

C++ Code

Node* findMin(Node* root) {

    if (root == nullptr) {
        return nullptr;
    }

    while (root->left != nullptr) {
        root = root->left;
    }

    return root;
}

8. C++ Program for Deletion in BST

The following function handles all three deletion cases.

Node* findMin(Node* root) {

    while (root != nullptr && root->left != nullptr) {
        root = root->left;
    }

    return root;
}

Node* deleteNode(Node* root, int key) {

    // Case: value not found or empty tree
    if (root == nullptr) {
        return nullptr;
    }

    // Search in left subtree
    if (key < root->data) {
        root->left = deleteNode(root->left, key);
    }

    // Search in right subtree
    else if (key > root->data) {
        root->right = deleteNode(root->right, key);
    }

    else {

        // Case 1 and 2:
        // Node has no left child
        if (root->left == nullptr) {

            Node* temp = root->right;

            delete root;

            return temp;
        }

        // Node has no right child
        else if (root->right == nullptr) {

            Node* temp = root->left;

            delete root;

            return temp;
        }

        // Case 3: Node has two children

        Node* temp = findMin(root->right);

        root->data = temp->data;

        root->right = deleteNode(root->right, temp->data);
    }

    return root;
}

Explanation

  • First, the function searches for the node that contains the required key.
  • If the node has no left child, its right child takes its place. This also handles a leaf node.
  • If the node has no right child, its left child takes its place.
  • If the node has two children, its inorder successor replaces its value.
  • The original successor node is then deleted.

9. Complete C++ Program: Insertion and Deletion

#include <iostream>
using namespace std;

struct Node {

    int data;
    Node* left;
    Node* right;

    Node(int value) {

        data = value;
        left = nullptr;
        right = nullptr;
    }
};

Node* insert(Node* root, int value) {

    if (root == nullptr) {
        return new Node(value);
    }

    if (value < root->data) {
        root->left = insert(root->left, value);
    }
    else if (value > root->data) {
        root->right = insert(root->right, value);
    }

    return root;
}

Node* findMin(Node* root) {

    while (root != nullptr && root->left != nullptr) {
        root = root->left;
    }

    return root;
}

Node* deleteNode(Node* root, int key) {

    if (root == nullptr) {
        return nullptr;
    }

    if (key < root->data) {
        root->left = deleteNode(root->left, key);
    }

    else if (key > root->data) {
        root->right = deleteNode(root->right, key);
    }

    else {

        if (root->left == nullptr) {

            Node* temp = root->right;

            delete root;

            return temp;
        }

        else if (root->right == nullptr) {

            Node* temp = root->left;

            delete root;

            return temp;
        }

        Node* temp = findMin(root->right);

        root->data = temp->data;

        root->right = deleteNode(root->right, temp->data);
    }

    return root;
}

void inorder(Node* root) {

    if (root == nullptr) {
        return;
    }

    inorder(root->left);

    cout << root->data << " ";

    inorder(root->right);
}

int main() {

    Node* root = nullptr;

    root = insert(root, 50);
    root = insert(root, 30);
    root = insert(root, 70);
    root = insert(root, 20);
    root = insert(root, 40);
    root = insert(root, 60);
    root = insert(root, 80);

    cout << "Before Deletion: ";
    inorder(root);

    root = deleteNode(root, 50);

    cout << "\nAfter Deletion: ";
    inorder(root);

    return 0;
}

Output

Before Deletion: 20 30 40 50 60 70 80

After Deletion: 20 30 40 60 70 80

10. Dry Run of Deletion with Two Children

Consider the following BST and delete 50.

              50
             /  \
           30    70
          / \    / \
        20  40  60  80
Step Operation Result
1 Find node 50 Node found
2 Check its children Two children exist
3 Find minimum in right subtree 60
4 Replace 50 with 60 Root becomes 60
5 Delete original 60 Successor removed

Final Inorder: 20 30 40 60 70 80

11. Inorder Predecessor as an Alternative

Instead of using the inorder successor, we can also use the inorder predecessor when deleting a node with two children.

The inorder predecessor is the next smaller value in inorder traversal. It is the maximum value in the left subtree.

For example, when deleting 50 from the earlier tree, the inorder predecessor is 40.

              40
             /  \
           30    70
          /      / \
        20      60 80

Both successor-based and predecessor-based deletion are valid approaches when implemented correctly.

12. Time Complexity

Insertion and deletion both depend on the height of the BST because they first follow a path from the root to the required position or node.

Operation Average Case Worst Case
Insertion O(log N) O(N)
Deletion O(log N) O(N)
Find Minimum O(log N) O(N)
Inorder Traversal O(N) O(N)

Space Complexity

  • Recursive insertion: O(H) call-stack space.
  • Recursive deletion: O(H) call-stack space.
  • Iterative minimum search: O(1) auxiliary space.

H is the height of the BST. For a balanced BST, H is approximately O(log N). For a skewed BST, H can become O(N).

13. Insertion vs Deletion

Feature Insertion Deletion
Purpose Add a new node. Remove an existing node.
Difficulty Relatively simple. More complex.
Cases Find an empty position. Leaf, one child, or two children.
BST Property Must be preserved. Must be preserved.
Average Time O(log N) O(log N)
Worst Time O(N) O(N)

14. Common Mistakes

  • Forgetting to return the updated root after insertion.
  • Not connecting the recursive result back to the left or right child pointer.
  • Deleting a node with one child without reconnecting its child to the parent.
  • Removing a node with two children without finding a valid replacement.
  • Replacing a node with its successor but forgetting to delete the successor from its original position.
  • Forgetting to free the removed node using delete.
  • Assuming insertion and deletion always take O(log N).

15. Applications

  • Dynamic Ordered Sets: Adding and removing values while maintaining order.
  • Dictionary Structures: Inserting and removing keys.
  • Database Concepts: Understanding how ordered tree structures are updated.
  • Range-Based Data: Maintaining values for range queries.
  • Scheduling Systems: Managing ordered values that change over time.

16. Important Interview Questions

Q1. What is insertion in a BST?

Insertion is the process of adding a new node at the correct position while maintaining the BST property.

Q2. What are the three deletion cases?

Deleting a leaf node, deleting a node with one child, and deleting a node with two children.

Q3. How do you delete a leaf node?

Remove the node and set the corresponding parent pointer to NULL.

Q4. How do you delete a node with one child?

Replace the node with its only child.

Q5. How do you delete a node with two children?

Replace its value with its inorder successor or predecessor, then delete that replacement node from its original position.

Q6. What is an inorder successor?

It is the smallest value in the right subtree of a node that has a right subtree.

Q7. What is the average time complexity of insertion?

O(log N) for a reasonably balanced BST.

Q8. What is the worst-case time complexity of deletion?

O(N), when the BST is skewed.

17. Practice Problems

  1. Insert 45 into a BST containing 50, 30, 70, 20, 40, 60, and 80.
  2. Write a recursive C++ program for BST insertion.
  3. Delete a leaf node from a given BST.
  4. Delete a node that has only a left child.
  5. Delete a node that has only a right child.
  6. Delete a node that has two children using its inorder successor.
  7. Implement deletion using the inorder predecessor.
  8. Find the minimum node in a BST.
  9. Explain why deletion is more complicated than insertion.
  10. Analyse the time complexity of insertion and deletion.

18. Summary

Insertion and deletion are essential operations in a Binary Search Tree. Insertion places a new value at the correct empty position. Deletion removes a node while preserving the BST ordering property.

  • Insertion follows comparisons to find an empty position.
  • A leaf node can be deleted directly.
  • A node with one child is replaced by its child.
  • A node with two children is replaced using its inorder successor or predecessor.
  • Both operations take O(H) time.
  • The worst-case time complexity is O(N).
Key Takeaway: Insertion and deletion must always preserve the BST property. Remember the three deletion cases carefully, especially the two-child case, where the inorder successor or predecessor is used to maintain the correct ordering.
Scroll to Top