Key Benefit: BSTs enable O(log n) insertion/removal (assuming a balanced tree) vs. O(n) for sorted arrays.


1. BST Insertion

Process

  1. Insert at leaf nodes for simplicity (avoids restructuring the tree).
  2. Traverse the tree similarly to search:
  3. Base Case: When reaching null, create a new node and return it to the parent.

Example: Inserting 6 into a BST

Code Overview

def insert(root, value):
    if not root:
        return TreeNode(value)  # Base case: create new node
    if value > root.val:
        root.right = insert(root.right, value)  # Assign to right
    elif value < root.val:
        root.left = insert(root.left, value)     # Assign to left
    return root


2. BST Removal

Key Cases

  1. Node has 0 or 1 child: Directly replace with its child (or null).
  2. Node has 2 children: Replace with the minimum node in the right subtree (or maximum in the left subtree).