Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 3 · syllabusAsked 3× in KTU papersLesson live

Binary search trees

Left smaller, right bigger: search, insert and the three delete cases — with the KTU questions worked out.

Syllabus says: “Binary Search Trees - Binary Search Tree Operations”

On this page · 12 sections
ormakkurippu ✎
Never-forget card

SMALLER → go LEFT, BIGGER → go RIGHT. Delete: 0 children → just remove; 1 child → child takes its place; 2 children → replace with the INORDER SUCCESSOR (smallest in the right subtree).

Picture it

Guessing a number with a friend saying “lower” or “higher”: every answer throws away half of what's left — exactly like walking down a BST.

Write this in the exam

A binary search tree is a binary tree in which, for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger than the node's key.

ചെറുത് ഇടത്തോട്ട്, വലുത് വലത്തോട്ട്!

What you will be able to do

  • Search (May 2026 Q14b) and insert in a BST.
  • Delete nodes in all three cases (Nov 2025 Q13a).
  • Build a BST from a sequence and find its height (model paper Q14b).

Worked example

Insert 35, 12, 47, 36, 52, 30, 25, 49 in this order:

1225303536474952
After all insertions.

Delete 30 — it has one child (25), so 25 takes its place:

12253536474952

Delete 47 — two children. Its inorder successor is the smallest key in its right subtree: go to 52, then left to 49. Copy 49 into 47's node and delete 49 from below:

122535364952
Final tree. Inorder check: 12 25 35 36 49 52 (sorted ✓).

Model paper Q14b — build and find the height

710111621355290
BST for 52, 35, 11, 7, 10, 90, 21, 16. Height = 4 edges (5 levels, if you count nodes).

Now watch it run

Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶.

Loading visualizer…

Algorithms

algorithm
Algorithm Search(t, key)
1. while t ≠ NULL do
2.     if key = t→data then return t
3.     else if key < t→data then t ← t→left
4.     else t ← t→right
5. return NULL                       // not found

Algorithm Insert(t, key)
1. if t = NULL then return newNode(key)
2. if key < t→data then t→left ← Insert(t→left, key)
3. else if key > t→data then t→right ← Insert(t→right, key)
4. return t                          // duplicates ignored

Algorithm Delete(t, key)
1. if t = NULL then return NULL
2. if key < t→data then t→left ← Delete(t→left, key)
3. else if key > t→data then t→right ← Delete(t→right, key)
4. else                              // found
5.     if t→left = NULL then return t→right     // 0 or 1 child
6.     if t→right = NULL then return t→left
7.     s ← t→right;  while s→left ≠ NULL do s ← s→left   // inorder successor
8.     t→data ← s→data
9.     t→right ← Delete(t→right, s→data)
10. return t

C implementation

bst.ctested ✓ 200/200 cases
C
/* Binary search tree — KTU PCCST303, Module 3 (KTU Nov 2025 Q13a, model Q14b)
 * Left subtree < node < right subtree. Duplicates are ignored.
 * Delete with two children: copy the inorder successor (smallest key of the right
 * subtree) into the node, then delete the successor.
 * Commands: I x | D x | S x | IN | PRE | POST | LEVEL
 * After every command: optional result line, then "TREE: " + parenthesised form,
 * e.g. 35(12(,30),47) — key(left,right), leaves written alone.                           */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node {
    int key;
    struct node *left, *right;
};
struct node *root = NULL;

struct node *newNode(int x) {
    struct node *n = malloc(sizeof *n);
    if (n == NULL) { printf("OUT OF MEMORY\n"); exit(1); }
    n->key = x; n->left = n->right = NULL;
    return n;
}

void insert(int x) {
    struct node **p = &root;
    while (*p != NULL) {
        if (x == (*p)->key) { printf("duplicate ignored\n"); return; }
        p = x < (*p)->key ? &(*p)->left : &(*p)->right;
    }
    *p = newNode(x);
}

void search(int x) {
    struct node *p = root;
    int comparisons = 0;
    while (p != NULL) {
        comparisons++;
        if (x == p->key) { printf("found after %d comparison%s\n", comparisons, comparisons > 1 ? "s" : ""); return; }
        p = x < p->key ? p->left : p->right;
    }
    printf("not found\n");
}

void deleteKey(int x) {
    struct node **p = &root, *t;
    while (*p != NULL && (*p)->key != x) p = x < (*p)->key ? &(*p)->left : &(*p)->right;
    if (*p == NULL) { printf("not found\n"); return; }
    t = *p;
    if (t->left != NULL && t->right != NULL) {       /* case 3: two children */
        struct node **s = &t->right;
        while ((*s)->left != NULL) s = &(*s)->left; /* inorder successor */
        t->key = (*s)->key;
        t = *s;
        *s = t->right;                               /* successor has no left child */
    } else *p = t->left != NULL ? t->left : t->right;   /* cases 1 and 2 */
    free(t);
    printf("deleted %d\n", x);
}

void inorder(struct node *t)   { if (t) { inorder(t->left); printf(" %d", t->key); inorder(t->right); } }
void preorder(struct node *t)  { if (t) { printf(" %d", t->key); preorder(t->left); preorder(t->right); } }
void postorder(struct node *t) { if (t) { postorder(t->left); postorder(t->right); printf(" %d", t->key); } }

void levelorder(void) {
    struct node *q[64];
    int front = 0, rear = 0;
    if (root) q[rear++] = root;
    while (front < rear) {
        struct node *t = q[front++];
        printf(" %d", t->key);
        if (t->left) q[rear++] = t->left;
        if (t->right) q[rear++] = t->right;
    }
}

void show(struct node *t) {
    if (t == NULL) return;
    printf("%d", t->key);
    if (t->left || t->right) { printf("("); show(t->left); printf(","); show(t->right); printf(")"); }
}

void freeTree(struct node *t) { if (t) { freeTree(t->left); freeTree(t->right); free(t); } }

int main(void) {
    char cmd[8];
    int x;
    while (scanf("%7s", cmd) == 1) {
        if (strcmp(cmd, "I") == 0 && scanf("%d", &x) == 1) insert(x);
        else if (strcmp(cmd, "D") == 0 && scanf("%d", &x) == 1) deleteKey(x);
        else if (strcmp(cmd, "S") == 0 && scanf("%d", &x) == 1) search(x);
        else if (strcmp(cmd, "IN") == 0) { printf("inorder:"); inorder(root); printf("\n"); }
        else if (strcmp(cmd, "PRE") == 0) { printf("preorder:"); preorder(root); printf("\n"); }
        else if (strcmp(cmd, "POST") == 0) { printf("postorder:"); postorder(root); printf("\n"); }
        else if (strcmp(cmd, "LEVEL") == 0) { printf("levelorder:"); levelorder(); printf("\n"); }
        else { printf("BAD COMMAND\n"); break; }
        printf("TREE: "); show(root); printf("\n");
    }
    freeTree(root);
    return 0;
}
Sample run · Nov 2025 Q13a · real output from gcc

Input (stdin)

I 35
I 12
I 47
I 36
I 52
I 30
I 25
I 49
IN
D 30
D 47

Output (stdout)

TREE: 35
TREE: 35(12,)
TREE: 35(12,47)
TREE: 35(12,47(36,))
TREE: 35(12,47(36,52))
TREE: 35(12(,30),47(36,52))
TREE: 35(12(,30(25,)),47(36,52))
TREE: 35(12(,30(25,)),47(36,52(49,)))
inorder: 12 25 30 35 36 47 49 52
TREE: 35(12(,30(25,)),47(36,52(49,)))
deleted 30
TREE: 35(12(,25),47(36,52(49,)))
deleted 47
TREE: 35(12(,25),49(36,52))

Open in the Code Lab →

Complexity

All are O(h), where h is the height. Self-balancing trees (AVL, red-black — beyond this syllabus) keep h = O(log n).
OperationAverage (random inserts)Worst (skewed)
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)

Common mistakes

  • Using the inorder predecessor when the question says successor (or vice versa).
  • Moving the successor's whole subtree instead of re-linking its right child.
  • Mixing height in edges with height in levels — state which one you mean.

Asked in KTU exams (3)

Quick check — can you get them all?

Question 1

Q1.Inorder successor of a node with two children is…

Question 2

Q2.BST from 52, 35, 11, 7, 10, 90, 21, 16 — height (edges)?

Question 3

Q3.Worst-case search time in a BST with n nodes?

Practice

Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.

Exam-ready summary

  • Left < node < right.
  • Search/insert: compare and go left or right. O(h).
  • Delete: leaf → remove; one child → bypass; two children → copy the inorder successor, then delete it.
  • Inorder traversal = sorted keys.

References

  • Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — §5.7 (Binary search trees)
  • Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — Ch. 12

Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.

Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)