Lesson 14 +30 XP

Binary Search Trees (BST)

Binary Search Trees (BST)

A Binary Search Tree (BST) is a binary tree that satisfies the BST Ordering Property at every node N:

  • Every key in N's left subtree is strictly less than N.key.
  • Every key in N's right subtree is greater than N.key.
  • Both left and right subtrees are themselves BSTs.

1. Search, Min/Max & Insertion

  1. Search (find): Start at root; if key == root->data return node; go left if key < root->data, right otherwise.
  2. Find Minimum / Maximum:
  • Minimum: Follow left pointers until node->left == NULL.
  • Maximum: Follow right pointers until node->right == NULL.
  1. Insertion: Search for key until reaching NULL and attach the new leaf node at that exact position.
C
struct BSTNode* insertBST(struct BSTNode* root, int key) {
    if (!root) return createBSTNode(key);
    if (key < root->data) root->left = insertBST(root->left, key);
    else if (key > root->data) root->right = insertBST(root->right, key);
    return root;
}

Build Trace: Inserting [45, 15, 79, 90, 10, 55, 12, 20, 50]:

  • 45 is root → 15 goes left, 79 goes right → 90 goes right of 79 → 10 left of 15, 55 left of 79 → 12 right of 10, 20 right of 15, 50 left of 55.
  • Inorder Traversal: 10, 12, 15, 20, 45, 50, 55, 79, 90 (always sorted!).

2. BST Deletion (3 Cases)

  1. Case 1 (Leaf Node, 0 children): Remove the node and set parent's link to NULL. (E.g., delete 12 above).
  2. Case 2 (1 Child): Bypass the node by connecting its parent directly to its single child, then free() the node. (E.g., delete 10 → 15-&gt;left becomes 12).
  3. Case 3 (2 Children): Replace the node's key with either:
  • Inorder Successor: Smallest key in its right subtree (leftmost node of right child), OR
  • Inorder Predecessor: Largest key in its left subtree (rightmost node of left child).

Then recursively delete that successor/predecessor (which is guaranteed to have at most 1 child!). (E.g., delete 45 → replace with Inorder Successor 50, then delete leaf 50.)

C
struct BSTNode* deleteNode(struct BSTNode* root, int key) {
    if (!root) return NULL;
    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) { struct BSTNode* t = root->right; free(root); return t; }
        if (!root->right) { struct BSTNode* t = root->left; free(root); return t; }
        struct BSTNode* succ = root->right;
        while (succ->left) succ = succ->left;
        root->data = succ->data;
        root->right = deleteNode(root->right, succ->data);
    }
    return root;
}

3. Complexity Analysis

  • Average Case (Balanced): O(log n) for Search, Insert, Delete.
  • Worst Case (Skewed Tree): O(n) - occurs when keys are inserted in sorted (or reverse-sorted) order, degenerating the BST into a linked list!

Worked Build from the Notes

Insert 39, 27, 45, 18, 29, 40, 54, 28, 43, 41, 54, 60 (duplicates go to the right, since the right subtree holds values ≥ the root):

TEXT
              39
           /      \
         27        45
        /  \      /   \
      18    29   40    54
           /       \     \
          28        43    54
                   /        \
                  41         60

Inorder: 18 27 28 29 39 40 41 43 45 54 54 60-sorted, which confirms the BST property.

BST Algorithms in Pseudocode (Gilberg &amp; Forouzan style)

TEXT
Algorithm findSmallestBST(root)
    if root.left is null: return root
    return findSmallestBST(root.left)

Algorithm findLargestBST(root)
    if root.right is null: return root
    return findLargestBST(root.right)

Algorithm searchBST(root, target)
    if root is null: return null              // not found
    if target < root.key: return searchBST(root.left, target)
    if target > root.key: return searchBST(root.right, target)
    return root                               // found

Algorithm addBST(root, newNode)
    if root is null: root = newNode; return root
    if newNode.key < root.key: root.left  = addBST(root.left,  newNode)
    else:                      root.right = addBST(root.right, newNode)
    return root

Algorithm deleteBST(root, dltKey)
    if root is null: return false
    if dltKey < root.key: return deleteBST(root.left,  dltKey)
    if dltKey > root.key: return deleteBST(root.right, dltKey)
    // node found
    if root.left is null:  root = root.right            // 0 or 1 child
    else if root.right is null: root = root.left
    else:                                              // 2 children
        dltPtr = findLargestBST(root.left)             // inorder predecessor
        root.key = dltPtr.key
        deleteBST(root.left, dltPtr.key)
    return true

The notes replace a two-child node by the largest node of its left subtree (inorder predecessor); using the smallest of the right subtree (inorder successor) is equally correct.

Deleting 45 from the tree above: 45 has two children; the largest key in its left subtree is 43. Copy 43 into 45's node, then delete the old 43 (which has one child, 41, so 41 moves up to take its place).

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Define Binary Search Tree (BST). Write C functions for Insertion and Deletion (all 3 cases) in a BST. (10 Marks)
  • Write: BST ordering invariant, insertBST(), and all 3 deletion cases (0 children, 1 child, 2 children using Inorder Successor/Predecessor) with deleteNode() C code.
  • Q2. Construct a BST for [45, 15, 79, 90, 10, 55, 12, 20, 50] and write its Inorder traversal. (5 Marks)
  • Write: Step-by-step tree diagram and sorted Inorder output (10, 12, 15, 20, 45, 50, 55, 79, 90).