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.
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 answerHide 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
| Feature | Heap | Tree (BST or general) |
|---|---|---|
| Structure | Always a complete binary tree, every level full except possibly the last, which fills from the left | May or may not be complete |
| Ordering | Parent 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 siblings | None, only the parent-child relation is constrained | Strict left and right positions carry meaning in a BST |
| Search for an arbitrary key | Inefficient, $O(n)$ | $O(\log n)$ in a balanced BST |
| Typical use | Priority queues, heap sort, finding the extreme element | Searching, ordered traversal, hierarchical data |
| Usual implementation | An array, with children of index $i$ at $2i+1$ and $2i+2$ | Linked nodes holding child pointers |
| Balance | Balanced by definition | May 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.
2080 ยท 10 marks
Explain AVL tree with example. Also, explain balancing algorithm for this tree.[10]
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]
2074 ยท 10 marks
Explain the procedure for construction of Huffman algorithm with example.[10]
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 answerHide answer
Application of Spanning Tree and MST Construction
Applications of Spanning Tree
Spanning trees have several important practical applications:
-
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.
-
Routing Algorithms: Network routing protocols (like OSPF, STP in Ethernet) use spanning trees to avoid loops and ensure packets reach every node.
-
Cluster Analysis: Used in machine learning and data mining to group similar data points.
-
Circuit Design: Used in designing electronic circuits to minimize the total wire length connecting components.
-
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):
| Edge | Weight |
|---|---|
| A-B | 4 |
| A-C | 3 |
| B-C | 2 |
| B-D | 5 |
| C-E | 6 |
| D-E | 7 |
| D-F | 4 |
| E-G | 3 |
| F-G | 8 |
| F-H | 5 |
| G-H | 2 |
Constructing MST using Kruskal's Algorithm
Step 1: Sort all edges in non-decreasing order of weight:
| Edge | Weight |
|---|---|
| B-C | 2 |
| G-H | 2 |
| A-C | 3 |
| E-G | 3 |
| A-B | 4 |
| D-F | 4 |
| B-D | 5 |
| F-H | 5 |
| C-E | 6 |
| D-E | 7 |
| F-G | 8 |
Step 2: Select edges one by one, avoiding cycles:
| Step | Edge Selected | Weight | Reason |
|---|---|---|---|
| 1 | B-C | 2 | No cycle, add |
| 2 | G-H | 2 | No cycle, add |
| 3 | A-C | 3 | No cycle, add |
| 4 | E-G | 3 | No cycle, add |
| 5 | A-B | 4 | Skip - A,B,C already connected (cycle) |
| 6 | D-F | 4 | No cycle, add |
| 7 | B-D | 5 | No cycle, connects {A,B,C} with {D,F} |
| 8 | F-H | 5 | No 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 Edge | Weight |
|---|---|
| B - C | 2 |
| G - H | 2 |
| A - C | 3 |
| E - G | 3 |
| D - F | 4 |
| B - D | 5 |
| F - H | 5 |
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.
2081 ยท 5 marks
Write short notes on: a. Breadth First traversal of graph b. TOH [5]
Show solved answerHide 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:
- Choose some vertex arbitrarily as the root (starting vertex).
- 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.
- From the set of vertices at Level 1, find other vertices that are connected by edges to Level 1 vertices. These form Level 2.
- Repeat the above step until all vertices are visited/added.
- 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:
- Only one disk can be moved at a time.
- A disk can only be placed on top of a larger disk or on an empty peg.
- 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):
- Move
n-1disks from S to A (using D as auxiliary) - Move the nth (largest) disk from S to D
- Move
n-1disks from A to D (using S as auxiliary)
Example (n = 3 disks, S -> D using A):
| Step | Move |
|---|---|
| 1 | S -> D |
| 2 | S -> A |
| 3 | D -> A |
| 4 | S -> D |
| 5 | A -> S |
| 6 | A -> D |
| 7 | S -> 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)
2079 ยท 5 marks
Find the MST of following graph using Prim's algorithm. [5]
2075 ยท 10 marks
Discuss depth first and breadth first traversal of a graph with suitable example.[10]
2074 ยท 5 marks
Discuss the Kruskal's algorithm with example. [5]
Shortest Path Algorithms
2080 ยท 5 marks
Write Dijkstra's algorithm to find shortest path between any two vertices of a graph. [5]
2077 ยท 10 marks
What is shortest path? Explain Dijkstra algorithm for finding shortest path using suitable example.[10]
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 answerHide 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.
2074 ยท 10 marks
Illustrate the algorithm for Binary search tree with example.[10]
2074 ยท 5 marks
Differentiate between pre-order traversal and in order traversal. [5]
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]
Make Unit 8 stick
Practice CSC211 with flashcards & quizzes