8 Trees And Graphs

Data Structures and Algorithms ยท Unit 8 ยท 8 hrs

Trees and Graphs

Exam-focused notes for Trees and Graphs (Data Structures and Algorithms, CSC211): what the TU syllabus asks and how it has actually been tested, with 18 solved past questions from this unit.

Trees and Graphs in short

This chapter moves from linear structures to two non-linear ones. A tree models hierarchical data through the binary search tree and its self balancing AVL variant; a graph models arbitrary pairwise relationships, explored here through its traversals, its minimum spanning tree algorithms and its single source shortest path algorithm.

Trees and Graphs: notes

Concept and Definitions, Basic Operations in Binary Tree, Tree Height, Level and Depth

A tree is a non-linear data structure consisting of a set of nodes connected by edges, with one distinguished node called the root; every other node is reached from the root through exactly one path, and the rest of the tree splits into disjoint subtrees hanging off the root. A binary tree restricts every node to at most two children, its left child and right child; each node together with its left and right subtrees is itself a possibly empty binary tree. A binary tree with $n$ leaves in which every non-leaf node has both children, a strictly binary tree, always has $2n-1$ nodes in total; a complete binary tree of depth $d$ has every level fully filled and so contains $2^{d+1}-1$ nodes.

The level of a node is its distance from the root, with the root itself at level $0$; the height (or depth) of a tree is the level of its deepest node, so a tree with a single node has height $0$, and a binary tree of height $h$ can hold at most $2^{h+1}-1$ nodes. The basic operations on a binary tree $T$ are Root(T) (return the root node), Father(n, T) (return the parent of node n, or NULL for the root), LeftChild(n, T) / RightChild(n, T) (return a child, or NULL if it does not exist), Sibling(n, T) (return the other child of n's parent), Info(n, T) (return the value stored at n), and Size(T) (return the number of nodes). In C, a node is represented as:

struct bnode {
    int info;
    struct bnode *left;
    struct bnode *right;
};
struct bnode *root = NULL;

Visiting every node of a tree exactly once is a traversal; the three standard orders differ only in when the root is visited relative to its subtrees. Preorder visits root, then left subtree, then right subtree; inorder visits left subtree, then root, then right subtree; postorder visits left subtree, then right subtree, then root. Each is naturally written as a short recursive function, for example preorder:

#include <stdio.h>

struct bnode {
    int info;
    struct bnode *left;
    struct bnode *right;
};

void preorder(struct bnode *node) {
    if (node == NULL) return;
    printf("%d ", node->info);
    preorder(node->left);
    preorder(node->right);
}

What this unit covers

  • Concept and Definitions, Basic Operations in Binary Tree, Tree Height, Level and Depth
  • Binary Search Tree, Insertion, Deletion, Traversals, Search in BST
  • AVL tree and Balancing algorithm, Applications of Trees
  • Definition and Representation of Graphs, Graph Traversal, Minimum Spanning Trees: Kruskal and Prims Algorithm
  • Shortest Path Algorithms: Dijksrtra Algorithm

AVL tree and Balancing algorithm, Applications of Trees

2081 ยท 10 marks

What is AVL tree? How heap differ from tree? Construct an AVL tree for data 24,12,8,15,35,30,57,40,45 and 78.[10]

Show solved answer

AVL Tree, Heap versus Tree, and Construction

What is an AVL tree?

An AVL tree, named after Adelson-Velsky and Landis who proposed it in 1962, is a self-balancing binary search tree. It keeps the ordering of a binary search tree, every key in the left subtree of a node being smaller than the node and every key in the right subtree larger, and adds a height condition at every node: the heights of the left and right subtrees may differ by at most one.

The condition is expressed through the balance factor

$$BF = h(\text{left subtree}) - h(\text{right subtree})$$

which must remain one of $-1$, $0$ or $+1$. If an insertion or deletion drives some balance factor to $+2$ or $-2$, the tree is repaired by a rotation, a local rearrangement of a few links that preserves the ordering while reducing the height. There are four cases, named by the two links leading from the unbalanced node towards the newly inserted key: LL is fixed by a single right rotation, RR by a single left rotation, LR by a left rotation followed by a right rotation, and RL by a right rotation followed by a left rotation. Because the height of an AVL tree on $n$ nodes stays $O(\log n)$, search, insertion and deletion all run in $O(\log n)$ time.

How a heap differs from a tree

FeatureHeapTree (BST or general)
StructureAlways a complete binary tree, every level full except possibly the last, which fills from the leftMay or may not be complete
OrderingParent is greater than or equal to its children (max-heap) or less than or equal to them (min-heap)In a BST, keys in the left subtree are smaller than the node and keys in the right subtree are larger
Order among siblingsNone, only the parent-child relation is constrainedStrict left and right positions carry meaning in a BST
Search for an arbitrary keyInefficient, $O(n)$$O(\log n)$ in a balanced BST
Typical usePriority queues, heap sort, finding the extreme elementSearching, ordered traversal, hierarchical data
Usual implementationAn array, with children of index $i$ at $2i+1$ and $2i+2$Linked nodes holding child pointers
BalanceBalanced by definitionMay degenerate unless a balancing scheme such as AVL is used

The essential point is that a heap constrains only the relation between a parent and its children and therefore supports fast access to the minimum or maximum, while a binary search tree constrains the whole ordering left to right and therefore supports fast search for any key.

Constructing an AVL tree for 24, 12, 8, 15, 35, 30, 57, 40, 45, 78

Throughout, the height of a leaf is counted as 1 and the height of an empty subtree as 0, and

$$BF(x) = h(\text{left subtree of } x) - h(\text{right subtree of } x)$$

must stay in ${-1, 0, +1}$. After each insertion the balance factors are checked upward from the new node, so that the lowest unbalanced ancestor is the one rotated.

Insert 24

24

The first key becomes the root and $BF(24) = 0$.

Insert 12

Since $12 < 24$, the key goes to the left of the root.

  24
 /
12

$BF(24) = 1 - 0 = +1$, still within range.

Insert 8

Since $8 < 24$ and $8 < 12$, the key becomes the left child of 12.

    24
   /
  12
 /
8

Now $BF(12) = 1 - 0 = +1$ is fine, but $BF(24) = 2 - 0 = +2$, so 24 is unbalanced. From 24 the path to the new key goes left and then left again, an LL case, repaired by a single right rotation at 24.

   12
  /  \
 8    24

$BF(12) = 1 - 1 = 0$, so the tree is balanced again.

Insert 15

Since $15 > 12$ the key goes right to 24, and $15 < 24$ makes it the left child of 24.

   12
  /  \
 8    24
     /
    15

$BF(24) = 1 - 0 = +1$ and $BF(12) = 1 - 2 = -1$. No rotation is needed.

Insert 35

Since $35 > 12$ and $35 > 24$, the key becomes the right child of 24.

   12
  /  \
 8    24
     /  \
    15   35

$BF(24) = 1 - 1 = 0$ and $BF(12) = 1 - 2 = -1$. No rotation is needed.

Insert 30

Since $30 > 12$ the key goes right to 24, $30 > 24$ sends it right to 35, and $30 < 35$ makes it the left child of 35.

   12
  /  \
 8    24
     /  \
    15   35
        /
      30

Checking upward from the new node, $BF(35) = 1 - 0 = +1$ is fine and

$$BF(24) = h(15) - h(35) = 1 - 2 = -1$$

is also fine, so node 24 is balanced. The root, however, gives

$$BF(12) = h(8) - h(24) = 1 - 3 = -2$$

so the lowest unbalanced node is the root 12, not 24. From 12 the path to the new key goes right to 24 and then right again into the subtree rooted at 35, which is the RR case, repaired by a single left rotation at 12. In that rotation 24 moves up to become the root and hands its left child 15 to 12.

      24
     /  \
   12    35
  /  \   /
 8   15 30

Now $BF(12) = 1 - 1 = 0$, $BF(35) = 1 - 0 = +1$ and $BF(24) = 2 - 2 = 0$, so the tree is balanced.

Insert 57

Since $57 > 24$ and $57 > 35$, the key becomes the right child of 35.

      24
     /  \
   12    35
  /  \   / \
 8   15 30  57

$BF(35) = 1 - 1 = 0$ and $BF(24) = 2 - 2 = 0$. No rotation is needed.

Insert 40

Since $40 > 24$ the key goes right to 35, $40 > 35$ sends it right to 57, and $40 < 57$ makes it the left child of 57.

      24
     /  \
   12    35
  /  \   / \
 8   15 30  57
            /
          40

Here $BF(57) = 1 - 0 = +1$,

$$BF(35) = h(30) - h(57) = 1 - 2 = -1, \qquad BF(24) = h(12) - h(35) = 2 - 3 = -1$$

Every balance factor is in range, so no rotation is needed.

Insert 45

The key travels right to 35, right to 57, left to 40, and since $45 > 40$ it becomes the right child of 40.

      24
     /  \
   12    35
  /  \   / \
 8   15 30  57
            /
          40
            \
             45

Now $BF(40) = 0 - 1 = -1$ is fine, but

$$BF(57) = h(40) - 0 = 2 - 0 = +2$$

so 57 is the lowest unbalanced node. From 57 the path goes left to 40 and then right to 45, which is the LR case: first a left rotation at 40, then a right rotation at 57. The subtree rooted at 57 therefore becomes

    45
   /  \
 40    57

and the whole tree is

      24
     /  \
   12    35
  /  \   / \
 8   15 30  45
            / \
          40   57

with $BF(45) = 1 - 1 = 0$, $BF(35) = 1 - 2 = -1$ and $BF(24) = 2 - 3 = -1$, all in range.

Insert 78

The key travels right to 35, right to 45, right to 57, and becomes the right child of 57.

      24
     /  \
   12    35
  /  \   / \
 8   15 30  45
            / \
          40   57
                 \
                  78

Checking upward, $BF(57) = 0 - 1 = -1$ and $BF(45) = h(40) - h(57) = 1 - 2 = -1$ are fine, but

$$BF(35) = h(30) - h(45) = 1 - 3 = -2$$

so 35 is the lowest unbalanced node. From 35 the path goes right to 45 and then right again into the subtree rooted at 57, the RR case, repaired by a single left rotation at 35, in which 45 moves up and hands its left child 40 to 35.

      24
     /  \
   12    45
  /  \   /  \
 8   15 35   57
        / \    \
      30   40   78

Now $BF(35) = 1 - 1 = 0$, $BF(57) = 0 - 1 = -1$, $BF(45) = 2 - 2 = 0$ and $BF(24) = 2 - 3 = -1$, so the tree is balanced.

Final AVL tree

            24
         /      \
       12         45
      /  \       /   \
     8   15    35     57
              /  \      \
             30  40      78

The balance factors are $0$ at 8, 15, 30, 40 and 78, $0$ at 12, $0$ at 35, $-1$ at 57, $0$ at 45 and $-1$ at the root 24, every one of them inside ${-1, 0, +1}$, so the tree satisfies the AVL property. It stands four levels deep, the fewest possible for 10 nodes, and four rotations were needed in all: a right rotation at 24 (LL) when 8 was inserted, a left rotation at 12 (RR) when 30 was inserted, a left-right double rotation at 57 when 45 was inserted, and a left rotation at 35 (RR) when 78 was inserted.

Open this answer on its own page โ†’

2080 ยท 10 marks

Explain AVL tree with example. Also, explain balancing algorithm for this tree.[10]

An AVL tree (named after inventors Adelson-Velsky and Landis, 1962) is a self-balancing Binary Search Tree (BST) in which the difference between the heights of the left and right subtrees of any node is at most 1. This difference is called the Balance Factor (BF): For a valid AVL tree, the balanc...

Open this answer on its own page โ†’

2079 ยท 10 marks

Why do we need to balance the binary search tree? Justify with an example. Create an AVL tree from the data 24, 12, 8, 15, 35, 30, 57, 40, 45, 78.[10]

A binary search tree gives $O(\log n)$ search, insertion and deletion only while its height stays close to $\log2 n$. The shape of the tree, however, depends entirely on the order in which the keys arrive, and nothing in the plain insertion rule prevents it from growing tall and thin. In the wors...

Open this answer on its own page โ†’

2074 ยท 10 marks

Explain the procedure for construction of Huffman algorithm with example.[10]

Huffman coding is a greedy algorithm used for lossless data compression. It assigns variable-length binary codes to characters based on their frequencies -- characters with higher frequencies get shorter codes and characters with lower frequencies get longer codes. This minimizes the total number...

Open this answer on its own page โ†’

Definition and Representation of Graphs, Graph Traversal, Minimum Spanning Trees

2081 ยท 5 marks

What is the application of spanning tree? Draw a MST of a graph containing any 8 vertices and 11 edges with arbitrary edge costs. [5]

Show solved answer

Application of Spanning Tree and MST Construction

Applications of Spanning Tree

Spanning trees have several important practical applications:

  1. Network Design: Used in designing minimum cost communication networks, electrical grids, and computer networks where all nodes must be connected with minimum wiring/cabling cost.

  2. Routing Algorithms: Network routing protocols (like OSPF, STP in Ethernet) use spanning trees to avoid loops and ensure packets reach every node.

  3. Cluster Analysis: Used in machine learning and data mining to group similar data points.

  4. Circuit Design: Used in designing electronic circuits to minimize the total wire length connecting components.

  5. Transportation Networks: Used to find the minimum cost road/rail network connecting all cities.


Minimum Spanning Tree (MST) - Example with 8 Vertices and 11 Edges

Graph Definition

Consider a graph G = (V, E) with:

  • Vertices: V = {A, B, C, D, E, F, G, H}
  • Edges with weights (11 edges):
EdgeWeight
A-B4
A-C3
B-C2
B-D5
C-E6
D-E7
D-F4
E-G3
F-G8
F-H5
G-H2

Constructing MST using Kruskal's Algorithm

Step 1: Sort all edges in non-decreasing order of weight:

EdgeWeight
B-C2
G-H2
A-C3
E-G3
A-B4
D-F4
B-D5
F-H5
C-E6
D-E7
F-G8

Step 2: Select edges one by one, avoiding cycles:

StepEdge SelectedWeightReason
1B-C2No cycle, add
2G-H2No cycle, add
3A-C3No cycle, add
4E-G3No cycle, add
5A-B4Skip - A,B,C already connected (cycle)
6D-F4No cycle, add
7B-D5No cycle, connects {A,B,C} with {D,F}
8F-H5No cycle, connects {D,F} with {G,H,E}

At this point we have 7 edges connecting all 8 vertices -- MST is complete.

Total MST Cost = 2 + 2 + 3 + 3 + 4 + 5 + 5 = 24


MST Diagram

A
|  \
3    2
|      \
C ---- B
        |
        5
        |
        D
        |
        4
        |
        F
        |
        5
        |
        H
        |
        2
        |
        G
        |
        3
        |
        E

MST Edges:

A ---3--- C ---2--- B ---5--- D ---4--- F ---5--- H ---2--- G ---3--- E
MST EdgeWeight
B - C2
G - H2
A - C3
E - G3
D - F4
B - D5
F - H5

Total Minimum Cost = 2 + 2 + 3 + 3 + 4 + 5 + 5 = 24

The MST contains exactly n - 1 = 7 edges for 8 vertices, which satisfies the spanning tree property.

Open this answer on its own page โ†’

2081 ยท 5 marks

Write short notes on: a. Breadth First traversal of graph b. TOH [5]

Show solved answer

Short Notes


a. Breadth First Search (BFS) Traversal of Graph

Definition: BFS is one of the simplest methods of graph searching/traversal. It explores a graph level by level, visiting all neighbors of a vertex before moving to the next level.

Algorithm / Steps:

  1. Choose some vertex arbitrarily as the root (starting vertex).
  2. Visit the root and add all vertices and edges that are incident on the root. These newly added vertices form Level 1 of the BFS tree.
  3. From the set of vertices at Level 1, find other vertices that are connected by edges to Level 1 vertices. These form Level 2.
  4. Repeat the above step until all vertices are visited/added.
  5. A queue data structure is used to keep track of vertices to be visited next.

Example:

Graph:
    A
   / \
  B   C
 / \
D   E

BFS Order: A -> B -> C -> D -> E

Key Features:

  • Uses a Queue (FIFO)
  • Visits vertices in order of their distance from the source
  • Guarantees the shortest path in an unweighted graph

b. Tower of Hanoi (TOH)

csc211-toh-3disk

Definition: Tower of Hanoi is a classic recursive problem that involves moving n disks from a source peg to a destination peg using an auxiliary (helper) peg, following specific rules.

Rules:

  1. Only one disk can be moved at a time.
  2. A disk can only be placed on top of a larger disk or on an empty peg.
  3. Only the top disk of any peg can be moved.

Recursive Algorithm: To move n disks from Source (S) to Destination (D) using Auxiliary (A):

  1. Move n-1 disks from S to A (using D as auxiliary)
  2. Move the nth (largest) disk from S to D
  3. Move n-1 disks from A to D (using S as auxiliary)

Example (n = 3 disks, S -> D using A):

StepMove
1S -> D
2S -> A
3D -> A
4S -> D
5A -> S
6A -> D
7S -> D

Total moves = 2^n - 1 = 2^3 - 1 = 7 moves

Key Features:

  • Classic example of recursion
  • Minimum number of moves required = 2^n - 1
  • Time Complexity: O(2^n)
Open this answer on its own page โ†’

2079 ยท 5 marks

Find the MST of following graph using Prim's algorithm. [5]

The question asks to find the MST of a graph using Prim's algorithm and provides "the following graph." However, no graph image, vertex list, edge list, or weight values are actually included in the text provided to me. Missing data: - The set of vertices - The set of edges - The weight of each e...

Open this answer on its own page โ†’

2078 ยท 5 marks

What is graph traversal? Explain. [5]

Graph traversal (also called graph search) is the process of visiting (checking and/or updating) each vertex in a graph systematically, exactly once. It is a technique used to visit all the nodes of a graph in a specific order, ensuring no vertex is visited more than once and no vertex is left un...

Open this answer on its own page โ†’

2077 ยท 5 marks

What is minimum spanning tree? Explain. [5]

A Minimum Spanning Tree is a connected weighted graph that is a spanning tree having the smallest possible sum of weights of its edges. More formally, given a connected weighted graph G = (V, E), a minimum spanning tree is a subset of edges that: - Connects all vertices (spans the entire graph) -...

Open this answer on its own page โ†’

2075 ยท 10 marks

Discuss depth first and breadth first traversal of a graph with suitable example.[10]

Graph traversal means visiting every vertex of a graph exactly once in a systematic manner. The two standard traversal techniques are: 1. Breadth First Search (BFS) 2. Depth First Search (DFS) --- BFS is one of the simplest methods of graph searching. A vertex is chosen arbitrarily as a root. All...

Open this answer on its own page โ†’

2074 ยท 5 marks

Discuss the Kruskal's algorithm with example. [5]

Kruskal's algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a connected, undirected, weighted graph. It builds the MST by selecting edges in increasing order of weight, skipping any edge that would form a cycle. --- 1. Sort all edges of the graph in non-decreasing or...

Open this answer on its own page โ†’

Shortest Path Algorithms

2080 ยท 5 marks

Write Dijkstra's algorithm to find shortest path between any two vertices of a graph. [5]

Dijkstra's algorithm finds the shortest path from a single source vertex to all other vertices in a weighted graph (digraph), assuming no negative weighted edges exist. The shortest distance from source V to any vertex V' is stored in that vertex, and the path is recorded using back pointers. ---...

Open this answer on its own page โ†’

2077 ยท 10 marks

What is shortest path? Explain Dijkstra algorithm for finding shortest path using suitable example.[10]

The shortest path between two vertices in a weighted graph is the path whose total sum of edge weights is minimum among all possible paths connecting those two vertices. - It is applicable in directed as well as undirected weighted graphs. - The result gives the minimum cost (distance) to travel ...

Open this answer on its own page โ†’

Binary Search Tree, Insertion, Deletion, Traversals, Search in BST

2078 ยท 10 marks

What is binary search tree? Write a program to implement insertion and deletion algorithms in binary search tree.[10]

Show solved answer

Binary Search Tree: Definition, Insertion and Deletion


Definition of Binary Search Tree (BST)

A Binary Search Tree (BST) is a binary tree that is either empty or in which every node contains a key (value) and satisfies the following conditions:

  • All keys in the left sub-tree of the root are smaller than the key in the root node.
  • All keys in the right sub-tree of the root are greater than the key in the root node.
  • The left and right sub-trees of the root are again binary search trees (recursive definition).

Example:

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

Here, every left child < parent < right child.


Node Structure

Each node in a BST contains:

  • A data/key field
  • A pointer to the left child
  • A pointer to the right child

C Program: BST Insertion and Deletion

#include <stdio.h>
#include <stdlib.h>

/* โ”€โ”€ Node structure โ”€โ”€ */
struct Node {
    int data;
    struct Node *left;
    struct Node *right;
};

/* โ”€โ”€ Helper: create a new node โ”€โ”€ */
struct Node* createNode(int value) {
    struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data  = value;
    newNode->left  = NULL;
    newNode->right = NULL;
    return newNode;
}

/* โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
   INSERTION
   โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
   Algorithm:
   1. If tree is empty, new node becomes root.
   2. If value < current node data, go LEFT.
   3. If value > current node data, go RIGHT.
   4. Repeat until NULL position found; insert there.
*/
struct Node* insert(struct Node *root, int value) {
    /* Base case: empty tree or reached insertion point */
    if (root == NULL) {
        return createNode(value);
    }

    if (value < root->data) {
        /* Insert in left sub-tree */
        root->left = insert(root->left, value);
    }
    else if (value > root->data) {
        /* Insert in right sub-tree */
        root->right = insert(root->right, value);
    }
    else {
        /* Duplicate keys are not inserted */
        printf("Value %d already exists in BST.\n", value);
    }

    return root;
}

/* โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
   FIND MINIMUM NODE
   (Used during deletion)
   Returns the node with minimum key
   in a given sub-tree (leftmost node).
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• */
struct Node* findMin(struct Node *root) {
    while (root->left != NULL) {
        root = root->left;
    }
    return root;
}

/* โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
   DELETION
   โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
   Three cases:
   Case 1: Node has NO child (leaf)
           --> Simply delete the node.

   Case 2: Node has ONE child
           --> Replace node with its child.

   Case 3: Node has TWO children
           --> Find in-order successor
               (smallest in right sub-tree).
           --> Copy successor's value to node.
           --> Delete the in-order successor.
*/
struct Node* deleteNode(struct Node *root, int value) {
    /* Base case: value not found */
    if (root == NULL) {
        printf("Value %d not found in BST.\n", value);
        return NULL;
    }

    if (value < root->data) {
        /* Value lies in left sub-tree */
        root->left = deleteNode(root->left, value);
    }
    else if (value > root->data) {
        /* Value lies in right sub-tree */
        root->right = deleteNode(root->right, value);
    }
    else {
        /* Node to be deleted is found */

        /* Case 1: Leaf node (no children) */
        if (root->left == NULL && root->right == NULL) {
            free(root);
            return NULL;
        }

        /* Case 2a: Only right child exists */
        else if (root->left == NULL) {
            struct Node *temp = root->right;
            free(root);
            return temp;
        }

        /* Case 2b: Only left child exists */
        else if (root->right == NULL) {
            struct Node *temp = root->left;
            free(root);
            return temp;
        }

        /* Case 3: Node has two children */
        else {
            /* Find in-order successor (min of right sub-tree) */
            struct Node *successor = findMin(root->right);

            /* Copy successor's value to current node */
            root->data = successor->data;

            /* Delete the in-order successor from right sub-tree */
            root->right = deleteNode(root->right, successor->data);
        }
    }

    return root;
}

/* โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
   IN-ORDER TRAVERSAL (Left-Root-Right)
   Prints BST in sorted order
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• */
void inorder(struct Node *root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->data);
        inorder(root->right);
    }
}

/* โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
   MAIN FUNCTION
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• */
int main() {
    struct Node *root = NULL;

    /* Inserting nodes */
    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);

    printf("Inorder traversal of BST: ");
    inorder(root);
    printf("\n");

    /* Delete a leaf node */
    root = deleteNode(root, 20);
    printf("After deleting 20: ");
    inorder(root);
    printf("\n");

    /* Delete a node with one child */
    root = deleteNode(root, 30);
    printf("After deleting 30: ");
    inorder(root);
    printf("\n");

    /* Delete a node with two children */
    root = deleteNode(root, 50);
    printf("After deleting 50: ");
    inorder(root);
    printf("\n");

    return 0;
}

Sample Output:

Inorder traversal of BST: 20 30 40 50 60 70 80
After deleting 20: 30 40 50 60 70 80
After deleting 30: 40 50 60 70 80
After deleting 50: 40 60 70 80

Explanation

Deleting 20 removes a leaf node directly. Deleting 30 removes a node with only one child (40), so 40 takes its place. Deleting 50 (the root, which now has two children 40 and 70) is handled by Case 3: the in-order successor, 60 (the smallest value in the right sub-tree rooted at 70), replaces 50's value, and the original node holding 60 is then removed from the right sub-tree. The in-order traversal after each deletion confirms that the BST property (left < parent < right at every node) is preserved throughout, which is why the printed sequence always stays sorted.

Open this answer on its own page โ†’

2075 ยท 5 marks

How do you traverse a binary tree? Discuss. [5]

Binary tree traversal is the process of visiting each node of a binary tree exactly once in a systematic order. Since a binary tree has three components (root, left subtree, right subtree), different orderings of visiting these components give different traversal methods. --- Consider the followi...

Open this answer on its own page โ†’

2074 ยท 10 marks

Illustrate the algorithm for Binary search tree with example.[10]

A Binary Search Tree (BST) is a binary tree that is either empty or in which every node contains a key (value) and satisfies the following conditions: - All keys in the left sub-tree of the root are smaller than the key in the root node. - All keys in the right sub-tree are greater than the key i...

Open this answer on its own page โ†’

2074 ยท 5 marks

Differentiate between pre-order traversal and in order traversal. [5]

Binary Tree Traversal means visiting each node in a tree exactly once in a systematic manner. Two of the three popular traversal methods are Pre-order and In-order traversal. --- The pre-order traversal of a non-empty binary tree is defined as follows: 1. Visit the root node (Root) 2. Traverse th...

Open this answer on its own page โ†’

Concept and Definitions, Basic Operations in Binary Tree, Tree Height, Level and Depth

2074 ยท 5 marks

What are the types of binary tree? Compare between them. [5]

A binary tree is a finite set of elements that is either empty or partitioned into three disjoint subsets: the root, the left subtree, and the right subtree, where each subtree is itself a binary tree. --- A binary tree in which every node has either 0 or 2 children. No node has exactly one child...

Open this answer on its own page โ†’