Skip to main content
Binary Trees & Graphs
CHAPTER 09 Beginner

BST Insertion and Deletion

Updated: May 17, 2026
10 min read

# CHAPTER 9

BST Insertion and Deletion

1. Introduction

In Chapter 8, we learned how to achieve blistering $O(\log N)$ search speeds by relying on the strict mathematical architecture of a Binary Search Tree (BST). But a database is not static. Users constantly register (Insertion) and delete their accounts (Deletion). Inserting a node into a BST is straightforward. Deleting a node, however, is one of the most mechanically complex algorithms in basic computer science. If you blindly delete a node that has children, those children become "orphaned," causing massive RAM leaks and severing the entire bottom half of the database matrix. We must perform careful geometric pointer surgery to heal the tree.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Trace the recursive path required to seamlessly insert a new leaf node into a BST.
  • Execute the 3 specific architectural rules of BST Deletion.
  • Understand the logic of finding the "Inorder Successor" to heal severed branches.
  • Write robust, crash-proof insertion and deletion code logic.

3. BST Insertion Algorithm

Inserting a new node is simple: You always insert as a new Leaf Node at the absolute bottom of the tree. You never wedge a new node into the middle and force existing branches to shift down.

The Strategy:

  1. 1. Compare the new value to the Root.
  1. 2. If it is smaller, plunge into the Left Subtree. If larger, plunge into the Right Subtree.
  1. 3. Keep plunging until you hit a NULL dead end.
  1. 4. Synthesize the new Node in RAM and link the final parent pointer to it.

Trace Example (Insert 13):

text
12345
      [10]
     /    \
   [5]    [15]
          /  \
        [12] [20]
  • Compare 13 to 10. 13 > 10 $\rightarrow$ Go Right.
  • Compare 13 to 15. 13 < 15 $\rightarrow$ Go Left.
  • Compare 13 to 12. 13 > 12 $\rightarrow$ Go Right.
  • Node 12 has no right child (NULL). Anchor the new node [13] here!

4. BST Deletion Algorithm

Deletion requires extreme architectural precision. The complexity changes entirely depending on how many children the targeted doomed node has. There are exactly 3 Scenarios:

Scenario 1: The Node is a Leaf (0 Children)

  • *Action:* The easiest execution. Because it supports no underlying architecture, simply delete it from RAM and set its parent's pointer to NULL.

Scenario 2: The Node has Exactly 1 Child

  • *Action:* The "Bypass" maneuver. Delete the target node, and take its singular child branch and directly link it to the target node's parent. (Like a grandparent legally adopting a grandchild after the parent vanishes).

Scenario 3: The Node has Exactly 2 Children (The Nightmare Scenario)

  • *Action:* You cannot delete it directly! If you delete the Root, you are left with two massive, disconnected Left and Right subtrees. You must find a mathematically perfect "Replacement Node" to slide into the severed position that respects all BST < and > constraints.
  • The Solution: Find the Inorder Successor.
  • The Inorder Successor is mathematically defined as the *absolute smallest node in the Right Subtree*.
  • To find it: Go right one step, then aggressively plunge all the way down to the extreme Left Leaf.
  • Copy the value of that Successor into the doomed node's spot.
  • Finally, securely delete that original Successor leaf from the bottom of the tree.

5. Step-by-Step Scenario 3 Trace

Delete Root 10:
text
12345
        [10] (DOOMED)
       /    \
     [5]    [15]
    /  \    /  \
  [2]  [7] [12] [20]
  1. 1. Identify 10 has two children. Do NOT delete the physical pointers.
  1. 2. Find the Inorder Successor (Smallest node in the Right Subtree).
  1. 3. Jump right to [15]. Plunge extreme left to [12]. The Successor is 12.
  1. 4. Overwrite the doomed node's data. (Change [10] to [12]).
  1. 5. Now, safely delete the original [12] leaf node from the bottom using Scenario 1 rules.
*The BST is mathematically healed! Everything to the left is still $< 12$. Everything to the right is still $> 12$!*

6. Code Execution: Insertion

Python (Recursive):
python
12345678910111213
def insert_bst(node, val):
    # Base Case: Hit a NULL slot, spawn the new Node
    if node is None:
        return Node(val)
        
    # Recursively traverse left or right
    if val < node.val:
        node.left = insert_bst(node.left, val)
    elif val > node.val:
        node.right = insert_bst(node.right, val)
        
    # Return the unchanged node pointer to re-stitch the tree
    return node 

7. Complexity Analysis

  • Time Complexity (Insert/Delete): $O(\log N)$ in a balanced tree, because the algorithm simply plunges straight down a singular branch. It degrades to horrific $O(N)$ if the tree is degenerate.
  • Space Complexity: $O(1)$ Iterative, $O(\log N)$ Recursive stack.

8. Common Mistakes

  • Incorrectly linking the Inorder Successor: When developers extract the Inorder Successor, they often forget that the successor might have a *Right Child* of its own (Scenario 2). You must execute proper Scenario 2 bypass deletion on the successor, you cannot just blindly delete it!

9. Exercises

  1. 1. Draw the resulting visual tree after inserting the sequence [50, 30, 70, 20, 40] into an empty BST.
  1. 2. In that generated tree, detail the precise structural pointer changes required to delete node 30.

10. MCQs with Answers

Question 1

When architecting an algorithm to insert a completely new data value into an existing, populated BST, where does the new node definitively attach itself?

Question 2

What defines the foundational algorithmic Time Complexity for an optimal BST insertion execution?

Question 3

When a database architect triggers a Deletion command upon a targeted BST node that possesses precisely zero children (a Leaf Node), what memory surgery must transpire?

Question 4

If a targeted deletion node mathematically supports exactly one singular downward child branch, what "Bypass" logic governs the localized pointer surgery?

Question 5

Why does targeting a node with exactly Two Children (Left and Right) invoke the "Nightmare Scenario" for BST algorithmic deletion constraints?

Question 6

To mathematically resolve a Two-Child deletion matrix without corrupting the overarching geometric < and > constraints, the algorithm must overwrite the doomed node utilizing its "Inorder Successor". What explicitly is an Inorder Successor?

Question 7

How does a search algorithm physically isolate the Inorder Successor within the structural Right Subtree matrix?

Question 8

After overwriting the Two-Child doomed node with the targeted integer data extracted from the Inorder Successor, what final cleanup phase must structurally execute?

Question 9

Is it geometrically and mathematically permissible to resolve a Two-Child deletion constraint utilizing an "Inorder Predecessor" rather than a Successor?

Q10. True or False: Because modern high-level languages like Python and Java utilize automated Garbage Collection engines, explicitly updating the parent null pointers during leaf deletion is technically unnecessary. a) True. The Garbage Collector senses the deletion. b) False. A Garbage Collector exclusively purges RAM objects that possess exactly zero active pointers directing toward them. If a parent node retains a legacy pointer linked to a "deleted" child, the OS is structurally forbidden from clearing the memory, generating a catastrophic massive memory leak. Answer: b) False. A Garbage Collector exclusively purges RAM objects that possess exactly zero active...

11. Interview Preparation

Top Interview Questions:
  • *Algorithmic Edge Cases:* "When resolving a Two-Child deletion using the Inorder Successor, is it mathematically possible for that Successor node to *also* have Two Children, trapping you in an infinite recursion?" *(Answer: No! The Inorder Successor is structurally discovered by plunging extreme Left. If it had a Left Child, it wouldn't be the Successor! Therefore, the Successor mathematically guarantees it has either 0 or 1 Right Child, easily resolved by base deletion cases!)*

12. Summary

BST manipulation is an exercise in extreme memory precision. Insertion safely spawns new data at the terminal geometric limits. Deletion forces software architects to execute highly complex pointer surgery, bypassing orphaned nodes or teleporting the Inorder Successor upward to perfectly seal severed structural branches without violating the algorithmic integrity of the database.

13. Next Chapter Recommendation

We have mastered the mechanics of manipulating a BST. But there is a silent, lethal problem. What if our dynamic Insertions constantly favor the right side? What if the tree degrades into a straight-line Linked List, destroying our $O(\log N)$ speed? In Chapter 10: Balanced Binary Trees, we examine the mathematical chaos of Degeneration and how hardware engineers define true geometric equilibrium.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·