0% found this document useful (0 votes)
66 views58 pages

BCS304 DS Module 4 Notes

Uploaded by

bheemanna171147
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views58 pages

BCS304 DS Module 4 Notes

Uploaded by

bheemanna171147
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Module 4

Trees (Contd..): Binary Search trees, Selection Trees, Forests, Representation of


Disjoint sets, Counting Binary Trees,
Graphs: The Graph Abstract Data Types, Elementary Graph Operations

Text Book: Chapter-5: 5.7 to 5.11, Chapter-6: 6.1, 6.2

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 1 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

4.1. Binary Search Trees


• A Binary Search Tree (BST) is a type of binary tree that maintains a specific order property, which
allows efficient searching, insertion, and deletion of elements.
• In a Binary search tree, the value of left node must be smaller than the parent node, and the value
of right node must be greater than the parent node.
• This rule is applied recursively to the left and right subtrees of the root.
o It is called a binary tree because each tree node has a maximum of two children.
o It is called a search tree because it can be used to search for the presence of a number in
O(log(n)) time.
• The properties that separate a binary search tree from a regular binary tree is
o All nodes of left subtree are less than the root node
o All nodes of right subtree are more than the root node
o Both subtrees of each node are also BSTs i.e. they have the above two properties

Representation
• BST is a collection of nodes arranged in a way where they maintain BST properties. Each node
has a key and an associated value.
• While searching, the desired key is compared to the keys in BST and if found, the associated value
is retrieved.
• Following is a pictorial representation of BST

• We observe that the root node key (27) has all less-valued keys on the left sub-tree and the higher
valued keys on the right sub-tree.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 2 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Basic Operations
• Insertion: Inserts an element in a tree.

• Deletion: Delete an element from a tree

• Search: Searches an element in a tree.

• Traversal

o Preorder Traversal: Traverses a tree in a pre-order manner.

o Inorder Traversal: Traverses a tree in an in-order manner.

o Postorder Traversal: Traverses a tree in a post-order manner.

Construction of Binary Search Tree


• Construct a Binary Search Tree (BST) for the following sequence of numbers-
50, 70, 60, 20, 90, 10, 40, 100
• When elements are given in a sequence, always consider the first element as the root node.
• Consider the given elements and insert them in the BST one by one.
• The binary search tree will be constructed as explained below-

1. Insertion
• To inserting a value in the correct position, try to maintain the rule that the left subtree is lesser
than root and the right subtree is larger than root.
• We keep going to either right subtree or left subtree depending on the value and when we reach a
point left or right subtree is null, we put the new node there.
• Algorithm
If node == NULL
return createNode(data)
if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
return node;

Insert 50: 50 is a first node it will become root node

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 3 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Insert 70: As 70 > 50, so insert 70 to the right of 50.

Insert 60
• As 60 > 50, so insert 60 to the right of 50.
• As 60 < 70, so insert 60 to the left of 70.

Insert 20: As 20 < 50, so insert 20 to the left of 50.

Insert 90:
• As 90 > 50, so insert 90 to the right of 50.
• As 90 > 70, so insert 90 to the right of 70.

Insert 10:
• As 10 < 50, so insert 10 to the left of 50.
• As 10 < 20, so insert 10 to the left of 20.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 4 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Insert 40:
• As 40 < 50, so insert 40 to the left of 50.
• As 40 > 20, so insert 40 to the right of 20.

Insert 100:
• As 100 > 50, so insert 100 to the right of 50.
• As 100 > 70, so insert 100 to the right of 70.
• As 100 > 90, so insert 100 to the right of 90.

• Example 2: Insert value 4 in to the following binary search Tree

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 5 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• We have attached the node but we still have to exit from the function without doing any damage
to the rest of the tree.
• This is where the return node; at the end comes in handy. In the case of NULL, the newly created
node is returned and attached to the parent node, otherwise the same node is returned without any
change as we go up until we return to the root.
• This makes sure that as we move back up the tree, the other node connections aren't changed.

2. Deleting Node from Binary Search Tree


• There are three cases for deleting a node from a binary search tree.
o Case 1: In the first case, the node to be deleted is the leaf node. In such a case, simply
delete the node from the tree.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 6 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

o Case 2: In the second case, the node to be deleted lies has a single child node. In such a
case follow the steps below:
▪ Replace that node with its child node.
▪ Remove the child node from its original position.

o Case 3: In the third case, the node to be deleted has two children. In such a case follow the
steps below:
▪ Get the inorder successor of that node.
▪ Replace the node with the inorder successor.
▪ Remove the inorder successor from its original position.

3. Search Operation
• The algorithm depends on the property of BST that if each left subtree has values below root and
each right subtree has values above the root.
• If the value is below the root, we can say for sure that the value is not in the right subtree; we need
to only search in the left subtree and if the value is above the root, we can say for sure that the
value is not in the left subtree; we need to only search in the right subtree.
• Algorithm
if root == NULL
return NULL;

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 7 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

if number == root->data
return root->data;
if number < root->data
return search(root->left)
if number > root->data
return search(root->right)

• Representation

C Program to implement Binary Search Tree


#include <stdio.h>
#include <stdlib.h>
struct node
{
int key;
struct node *left;
struct node *right;
};

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 8 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

// Create a node
struct node *newNode(int item) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

// Inorder Traversal
void inorder(struct node *root) {
if (root != NULL) {
inorder(root->left); // Traverse left
printf("%d\t", root->key); // Traverse root
inorder(root->right); // Traverse right
}
}

// Preorder Traversal
void preorder(struct node *root) {
if (root != NULL) {
printf("%d\t", root->key); // Traverse root
preorder(root->left); // Traverse left
preorder(root->right); // Traverse right
}
}

// Postorder Traversal
void postorder(struct node *root) {
if (root != NULL) {
postorder(root->left); // Traverse left
postorder(root->right); // Traverse right
printf("%d\t", root->key); // Traverse root
}
}

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 9 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs
// Insert a node

struct node *insert(struct node *node, int key){


// Return a new node if the tree is empty
if (node == NULL)
return newNode(key);

// Traverse to the right place and insert the node

if (key < node->key)


node->left = insert(node->left, key);
else
node->right = insert(node->right, key);

return node;
}

//Search

void search(struct node *node, int key){


// Return a new node if the tree is empty
if (node == NULL) {
printf(" \nKey not found ");
return;
}
if(key == node->key)
printf("\nKey found: %d",key);
if (key < node->key)
return search(node->left,key);
if (key > node->key)
return search(node->right,key);
}

// Find the inorder successor

struct node *minValueNode(struct node *node){


struct node *current = node;

// Find the leftmost leaf


while (current && current->left != NULL)
current = current->left;
return current;

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 10 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

// Deleting a node
struct node *deleteNode(struct node *root, int key){
// Return if the tree is empty
if (root == NULL)
return root;
// Find the node to be deleted
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);

else {
// If the node is with only one child or no child
if (root->left == NULL) {
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL) {
struct node *temp = root->left;
free(root);
return temp;
}

// If the node has two children


struct node *temp = minValueNode(root->right);
// Place the inorder successor in position of the node to be deleted
root->key = temp->key;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->key);
}
return root;
}

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 11 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

int main() {
struct node *root = NULL;
root = insert(root, 8);
root = insert(root, 3);
root = insert(root, 1);
root = insert(root, 6);
root = insert(root, 7);
root = insert(root, 10);
root = insert(root, 14);
root = insert(root, 4);
printf("Inorder traversal: ");
inorder(root);
printf("\nAfter deleting 10\n");
root = deleteNode(root, 10);
printf("\nInorder traversal: ");
inorder(root);
printf("\nPreorder traversal: ");
preorder(root);
printf("\nPostorder traversal: ");
postorder(root);
search(root,8);
}

4.2. Application of Trees: Evaluation of Expression.


• A binary expression tree is a binary tree, where the operators are stored in the tree’s internal nodes,
and the leaves contain constants.
• Assume that each node of the binary expression tree has zero or two children. Given a simple
expression tree, consisting of basic binary operators i.e., + , – ,* and / and some integers,
evaluate the expression tree.
• We can evaluate an expression tree by applying the operator at the root to values obtained by
recursively evaluating left and right subtrees. This can be easily done by traversing the expression
tree using postorder traversal

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 12 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Program
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
char item;
struct node * left;
struct node * right;
}*Btree;

Btree root;
char expression[25]="91+24*2*+3";
Btree stack[25];
int stackPtr = -1;

void push(Btree root) {


stack[++stackPtr] = root;
}

Btree pop() {
return (stack[stackPtr--]);
}

void operandFunc(char var) {


Btree root = (Btree)malloc(sizeof(struct node));
root->item= var;
root->left= NULL;
root->right= NULL;
push(root);

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 13 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

}
void operatorFunc(char var) {
Btree root = (Btree)malloc(sizeof(struct node));
root->item = var;
root->right = pop();
root->left = pop();
push(root);
}

int calculate(char operator,int op1,int op2) {


printf("Operator = %c , num1 = %d, num2 = %d\n",operator,op1,op2);
switch(operator) {
case '+': return(op1+op2);
break;
case '-': return(op1-op2);
break;
case '*': return(op1*op2);
break;
case '/': return(op1/op2);
break;
case '%': return(op1%op2);
break;
/* case '$': return pow(op1,op2);
break; */
default: printf("\n illegal operation.");
}
}

int isOperand(char var) {


switch(var) {
case '+':
case '-':
case '*':
case '/':

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 14 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

case '$':
case '%': return 0;
default: return 1;
}
}

int solve(Btree root) {


Btree temp = root;
char num1,num2;
char operator;
int result;
if(temp) {
Btree LEFTP = temp->left;
Btree RIGHTP = temp->right;
if(LEFTP) {
if(isOperand(LEFTP->item)) {
num1 = LEFTP->item;
}
else {
num1 = solve(LEFTP);
}
}

if(RIGHTP) {
if(isOperand(RIGHTP->item)) {
num2 = RIGHTP->item;
}
else {
num2 = solve(RIGHTP);
}
}
operator = temp->item;
result = calculate(operator,num1-'0',num2-'0');
temp->item = (result+'0');

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 15 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

return root->item;
}
return 0;
}

int main() {
int count = 0;
printf("Please enter a postfix expression\n");
//gets(expression);
puts(expression);
for(count = 0;expression[count]!='\0';count++) {
switch(expression[count]) {
case '+':
case '-':
case '*':
case '/':
case '^':
case '%':
case '$': operatorFunc(expression[count]);
break;
default: operandFunc(expression[count]);
}
}

printf(" \n The stack pointer value= %d",stackPtr);


if(stackPtr==0) {
printf("\n\nThe result = %d",solve(stack[stackPtr])-'0');
printf("\n\n");
}
else {
printf("Incomplete / Incorrect postfix expression given!\n");
return 0;
}
}

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 16 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• Stack Tracing
o If an expression consists of operand create a node assign right and left as NULL, data as
operand and push the node into stack.
o If expression consists operator create node assign operator as a node value, and assign right
of node, left of node by popping stack then push the operator node into the stack.
o Continue the above till end of expression and evaluate the expression.

Step 1: expression [0] consists of ‘9’ it is an operand, create node and push into the stack (Fig. 1)
Step 2: expression [1] consists of ‘1’ it is an operand create node and push into the stack. (Fig. 2)
Step 3: expression [2] consists of ‘+’ it is an operator create node assign right and left by popping
stack and push operator node into stack. (Fig. 3)

Fig. 1 Fig. 2 Fig. 3

Step 4: expression [3] consists of ‘2’ it is an operand create node and push into the stack. (Fig. 4)
Step 5: expression[4] consists of ‘4’ it is an operand create node and push into the stack. (Fig. 5)

Fig. 4 Fig. 5
Step 6: expression [5] consists of ‘*’ it is an operator create node assign right and left by popping
stack and push operator node into stack. (Fig. 6)
Step 7: expression[6] consists of ‘2’ it is an operand create node and push into the stack. (Fig. 7)

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 17 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Fig. 6 Fig. 7

Step 8: expression [7] consists of ‘*’ it is an operator create node assign right and left by popping
stack and push operator node into stack. (Fig. 8)
Step 9: expression [8] consists of ‘+’ it is an operator create node assign right and left by popping
stack and push operator node into stack. (Fig. 9)

.
Fig. 8 Fig. 9
Step 10: expression [9] is ‘\0’ (NULL) character end of expression. As stack consists of single
element, evaluate the expression.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 18 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

4.3. Selection Trees (Tournament Trees)


• The Tournament tree is a complete binary tree with n external nodes and n – 1 internal nodes.
• The external nodes represent the players, and the internal nodes are representing the winners of
the match between the two players. This tree is also known as Selection tree.

4.3.1. Properties of Tournament trees


• The value of every internal node is always equal to one of its children.
• A tournament tree can have holes. The tournament tree having nodes less than 2 ^ (n+1) -1 contains
holes. The hole represents a player or team's absence and can be anywhere in the tree.
• Every node in a tournament tree is linked to its predecessor and successor, and unique paths exist
between all nodes.
• It is a type of binary heap (min or max heap). Or we can say it is the application of heaps.
• The root node represents the winner of the tournament.
• To find the winner or loser (best player) of the match, we need N-1 comparisons.

4.3.2. Types of tournament trees:


• Winner Tree, and
• Loser Tree

Winner Tree
• Winner tree is a complete binary tree, in which each node is representing the smaller or greater of
its two children
• The root is holding the smallest or greatest node of the tree. When the root has smaller value then
the winner tree is referred to as the minimum winner tree, and when the root has larger value, then
the tree is referred to as the maximum winner tree.
• It is easy to see that winner tree can be formed in O(log n) time.

Example 1
• Suppose there are some keys, 3, 5, 6, 7, 20, 8, 2, 9

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 19 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• The tournament's winner is always the smallest or the greatest of all the players or values and can
be found in O(1).
• The time needed to create the winner tree is O(Log N), where N represents the number of players.

Example 2
• Eight players participate in a tournament where a number represents each player, from 1 to 8. The
pairings of these players are given below:
Group A: 1, 3, 5, 7 (Matches: 1 - 7 and 3 - 5)
Group B: 2, 4, 6, 8 (Matches: 2 - 6, and 4 - 8)
• Winning Criteria - The player having the largest value wins the match. Represent the winner tree
(maximum winner tree) for this tournament tree.
• The winner tree (maximum winner tree) is represented below in the figure:

• Here, the tree formed is a max heap, the value of all the parents is either equal to or larger than its
children, and the winner is 8, which is the largest of all the players.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 20 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Looser Tree
• In a tournament tree, when the internal nodes are used to represent the loser of the match between
two, then the tree obtained is referred to as the loser tree. When the loser is the smaller value then
the loser tree is referred to as the minimum loser tree, and when the loser is the larger value, then
the loser tree is referred to as the maximum loser tree.
• It is also called the minimum or maximum loser tree. The same idea is also applied here, the loser
(or parent) is always equal to one of its children, and the loser is always the greatest or smallest of
all the players and can be found in O(1). Also, the time needed to create a loser tree is O(Log N),
where N is the number of players.

• Suppose there are some keys, 10, 2, 7, 6, 5, 9, 12, 1. So we will create minimum winner tree at
first.

• Now, we will store looser of the match in each internal node. (All Max Values are loosers)

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 21 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Example
• Eight players participate in a tournament where a number represents each player, from 1 to 8. The
pairings of these players are given below:
Group A: 1, 3, 5, 7 (Matches: 1 - 7 and 3 - 5)
Group B: 2, 4, 6, 8 (Matches: 2 - 6, and 4 - 8)
• The loser tree (minimum loser tree) obtained is shown in the given figure:

4.3.3. Application of Tournament Trees:


• It can find the maximum or minimum value in an array.
• It is generally used in sorting.
• It can be used in M-way merges.
• It is used to find the median of the sorted array
• It is also used in the truck loading problem

4.3.4. Sorting Elements


Example: 9 5 1 7 8 12 6 4
• Construct max Winner tree

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 22 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• Take the max Element and Place it in Array last position and place -99 in the Max element at Leaf
Node.
• Continue this process until all nodes are considered and resultant array will be in order

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 23 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 24 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 25 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

4.4. Forests
• A forest is a group of scattered trees.
• The following are the fundamental traits of forests:
o Multiple Trees: Two or more distinct tree structures make up a forest. The root nodes
and hierarchies of these trees may differ.
o Disconnected Trees: A forest does not contain a single root node that connects all of
its parts, unlike a single tree. As an alternative, no two trees in the forest are
interdependent.
o No Cycles Within Trees: While individual trees in a forest may go through cycles,
there aren't any cycles that connect different trees in the forest
• An illustration of a forest may be found here.

4.4.1. Common Types of Forests:


• Disjoint-Set Forest: A well-known illustration of forests is disjoint-set data structures, often
known as union-find. Each element in this structure is a part of a different set, and sets are
depicted as trees in a forest.
• Expression Forest: Expressions are sometimes represented as a forest of syntax trees with
each tree denoting a subexpression in certain compiler and parsing applications.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 26 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

4.4.2. Applications of Forest Data Structure


• Social networking websites: Tree and graph data structures are used by social networking
services (like Facebook, LinkedIn, Twitter, etc.) to describe their data. You build a forest of
two people when you work on adding two individuals as friends.
• Big data web scrapers: The main page serves as the root node, and the consecutive
hyperlinks from that page serve as the nodes for the remainder of the Tree in a website's
organizational structure, which resembles a tree. When Web scrapers collect information
from several similar websites, they display it as a forest of trees.
• Operating system Storage: You would be able to view different discs in the system, such
as C drive (C:), D drive (D:), etc., if you were using a Windows-based operating system.
Each drive may be compared to a distinct tree, while the entirety of the storage can be
compared to a forest.

4.4.3. Applications of Forest Data Structure


• Structure:
➢ A tree is a single-root, single-hierarchical structure.
➢ A forest is made up of numerous scattered trees, each having its own root.
• Connectedness:
➢ Every node in a tree is joined to a single root.
➢ The trees in a forest are separate from one another and not always interconnected.
• Root Nodes
➢ A single root node exists in a tree.
➢ One root node for each tree inside a forest is possible.
• Hierarchy
➢ A tree's parent-child relationships are clearly specified in its well-defined hierarchical
structure.
➢ Each tree hierarchy in a forest has its own unique structure.
• Applications
➢ For common activities including sorting (heap sort), searching (binary search trees), and
displaying hierarchical data (file systems), trees are frequently utilized.
➢ In situations when several discontinuous structures must be managed separately, such as
parsing expression grammars or disjoint-set data structures, forests are used.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 27 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

4.4.4. Conversion of General tree into Binary Tree


• Root of binary tree = Root of general tree
• Left child of node in binary tree = Left most child of the node in the general tree.
• Right child of anode in binary tree = Right siblings of the node in general tree.
• Example:

Step 1: As point no 1 A is binary tree Root


Step 2: In general tree left most of A is B, as point no.2 A of left is B
Step 3: Consider E in general tree, B’s left most is E

Step 1 Step 2 Step 3

Step 4: Now Left child of E is Nil, to proceed with point no.3 to draw right child, Root node A does
not have right siblings as it is a root node in general tree.
Step 5: B has right sibling i.e C, now C is right child of B in binary tree
Step 6: In the above E does not have leftmost child or right sibling, hence E is leaf node.
Step 7: C has left most child which is F, now F is left child of C in binary tree

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 28 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Step 5 Step 7

Step 8: F does not have left child in general tree, but it has right sibling G, Now G is right child of F
in binary tee
Step 9: G does not have left child in general tree, but it has right sibling H, Now H is right child of G
in binary tee

Step 8 Step 9
Step 10: H does not both left most child and right siblings in general node hence it is an leaf node in
the binary tree.
Step11: C has right sibling D in general tree, hence D is a right child of C
Step 12: D has its left most child I in general tree, hence I is the right child of D

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 29 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Step 11 Step 12

Step 13: I does not have left child, but it has right sibling J, hence J is right of I
Step 14: J has left most child as K

Step 13 Step 14

4.4.5. Conversion of Forest into Tree


Consider the following forest

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 30 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• Convert each general tree into a binary tree using above procedure

• Now first tree root of right child is next tree i.e A and right child is G
• Similarly, G right child is J
• Now the Binary tree is

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 31 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

4.5. Representation of Disjoint sets


• The disjoint set can be defined as the subsets where there is no common element between the two
sets.
• The disjoint set data structure is also known as union-find data structure and merge-find set.
• It is a data structure that contains a collection of disjoint or non-overlapping sets.
• The disjoint set means that when the set is partitioned into the disjoint subsets.
• A union-find algorithm is an algorithm that performs two useful operations on such a data
structure:
o Find: Determine which subset a particular element is in. This can determine if two elements
are in the same subset.
o Union: Join two subsets into a single subset. Here first we have to check if the two subsets
belong to the same set. If not, then we cannot perform union.

Applications of Disjoint set Union:


1. Kruskal’s Minimum Spanning Tree Algorithm.
2. Job Sequencing Problem.
3. Cycle Detection
4. Number of pairs
5. City With the Smallest Number of Neighbors at a Threshold Distance

Example: Consider 2 disjoint sets

s1 = {1, 2, 3, 4}
s2 = {5, 6, 7, 8}
• We have two subsets named s1 and s2.
• The s1 subset contains the elements 1, 2, 3, 4, while s2 contains the elements 5, 6, 7, 8. Since there
is no common element between these two sets, we will not get anything if we consider the

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 32 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

intersection between these two sets. This is also known as a disjoint set where no elements are
common.

• To perform the operations in the above case, we use only two operations, i.e., find and union.
• In the case of find operation, we have to check that the element is present in which set.

• Suppose we want to perform the union operation on these two sets. First, we have to check whether
the elements on which we are performing the union operation belong to different or same sets.
• If they belong to the different sets, then we can perform the union operation; otherwise, not.
• For example, we want to perform the union operation between 4 and 8. Since 4 and 8 belong to
different sets, so we apply the union operation.
• Once the union operation is performed, the edge will be added between the 4 and 8 shown as
below:

• When the union operation is applied, the set would be represented as:
s1Us2 = {1, 2, 3, 4, 5, 6, 7, 8}

• Suppose we add one more edge between 1 and 5. Now the final set can be represented as:

s3 = {1, 2, 3, 4, 5, 6, 7, 8}

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 33 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• If we consider any element from the above set, then all the elements belong to the same set; it
means that the cycle exists in a graph.

How can we detect a cycle in a graph?


• We will understand this concept through an example. Consider the below example to detect a cycle
with the help of using disjoint sets.

U = {1, 2, 3, 4, 5, 6, 7, 8}

• Each vertex is labelled with some weight. There is a universal set with 8 vertices. We will consider
each edge one by one and form the sets.
• First, we consider vertices 1 and 2. Both belong to the universal set; we perform the union
operation between elements 1 and 2. We will add the elements 1 and 2 in a set s1 and remove these
two elements from the universal set shown below:
s1 = {1, 2}

• The vertices that we consider now are 3 and 4. Both the vertices belong to the universal set; we
perform the union operation between elements 3 and 4. We will form the set s3 having elements 3
and 4 and remove the elements from the universal set shown as below:
s2 = {3, 4}

• The vertices that we consider now are 5 and 6. Both the vertices belong to the universal set, so we
perform the union operation between elements 5 and 6. We will form the set s3 having elements 5
and 6 and will remove these elements from the universal set shown as below:
s3 = {5, 6}

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 34 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• The vertices that we consider now are 7 and 8. Both the vertices belong to the universal set, so we
perform the union operation between elements 7 and 8. We will form the set s4 having elements 7
and 8 and will remove these elements from the universal set shown as below:
s4 = {7, 8}

• The next edge that we take is (2, 4). The vertex 2 is in set 1, and vertex 4 is in set 2, so both the
vertices are in different sets. When we apply the union operation, then it will form the new set
shown as below:
s5 = {1, 2, 3, 4}

• The next edge that we consider is (2, 5). The vertex 2 is in set 5, and the vertex 5 is in set s3, so
both the vertices are in different sets. When we apply the union operation, then it will form the
new set shown as below:
s6 = {1, 2, 3, 4, 5, 6}

• Now, two sets are left which are given below:


s4 = {7, 8}
s6 = {1, 2, 3, 4, 5, 6}

• The next edge is (1, 3). Since both the vertices, i.e.,1 and 3 belong to the same set, so it forms a
cycle. We will not consider this vertex.

• The next edge is (6, 8). Since both vertices 6 and 8 belong to the different vertices s4 and s6, we
will perform the union operation. The union operation will form the new set shown as below:
s7 = {1, 2, 3, 4, 5, 6, 7, 8}

• The last edge is left, which is (5, 7). Since both the vertices belong to the same set named s7, a
cycle is formed.

How can we represent the sets graphically?


• We have a universal set which is given below:
U = {1, 2, 3, 4, 5, 6, 7, 8}
We will consider each edge one by one to represent graphically.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 35 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

First, we consider the vertices 1 and 2, i.e., (1, 2) and represent them through graphically shown
as below:

• In the above figure, vertex 1 is the parent of vertex 2.


• Now we consider the vertices 3 and 4, i.e., (3, 4) and represent them graphically shown as below:

• In the above figure, vertex 3 is the parent of vertex 4.


• Consider the vertices 5 and 6, i.e., (5, 6) and represent them graphically shown as below:

• In the above figure, vertex 5 is the parent of vertex 6.


• Now, we consider the vertices 7 and 8, i.e., (7, 8) and represent them through graphically shown
as below:

• In the above figure, vertex 7 is the parent of vertex 8.


• Now we consider the edge (2, 4). Since 2 and 4 belong to different sets, so we need to perform the
union operation. In the above case, we observe that 1 is the parent of vertex 2 whereas vertex 3 is
the parent of vertex 4. When we perform the union operation on the two sets, i.e., s1 and s2, then
1 vertex would be the parent of vertex 3 shown as below:

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 36 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• The next edge is (2, 5) having weight 6. Since 2 and 5 are in two different sets so we will perform
the union operation. We make vertex 5 as a child of the vertex 1 shown as below:

• We have chosen vertex 5 as a child of vertex 1 because the vertex of the graph having parent 1 is
more than the graph having parent 5.

• The next edge is (1, 3) having weight 7. Both vertices 1 and 3 are in the same set, so there is no
need to perform any union operation. Since both the vertices belong to the same set; therefore,
there is a cycle. We have detected a cycle, so we will consider the edges further.

How can we detect a cycle with the help of an array?


• The above graph contains the 8 vertices. So, we represent all these 8 vertices in a single array.
Here, indices represent the 8 vertices. Each index contains a -1 value. The -1 value means the
vertex is the parent of itself.

• Now we will see that how we can represent the sets in an array.
• First, we consider the edge (1, 2). When we find 1 in an array, we observe that 1 is the parent of
itself. Similarly, vertex 2 is the parent of itself, so we make vertex 2 as the child of vertex 1. We
add 1 at the index 2 as 2 is the child of 1. We add -2 at the index 1 where '-' sign that the vertex 1
is the parent of itself and 2 represents the number of vertices in a set.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 37 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• The next edge is (3, 4). When we find 3 and 4 in array; we observe that both the vertices are parent
of itself. We make vertex 4 as the child of the vertex 3 so we add 3 at the index 4 in an array. We
add -2 at the index 3 shown as below:

• The next edge is (5, 6). When we find 5 and 6 in an array; we observe that both the vertices are
parent of itself. We make 6 as the child of the vertex 5 so we add 5 at the index 6 in an array. We
add -2 at the index 5 shown as below:

• The next edge is (5, 6). When we find 5 and 6 in an array; we observe that both the vertices are
parent of itself. We make 6 as the child of the vertex 5 so we add 5 at the index 6 in an array. We
add -2 at the index 5 shown as below:

• The next edge is (7, 8). Since both the vertices are parent of itself, so we make vertex 8 as the child
of the vertex 7. We add 7 at the index 8 and -2 at the index 7 in an array shown as below:

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 38 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• The next edge is (2, 4). The parent of the vertex 2 is 1 and the parent of the vertex is 3. Since both
the vertices have different parent, so we make the vertex 3 as the child of vertex 1. We add 1 at
the index 3. We add -4 at the index 1 as it contains 4 vertices.
• Graphically, it can be represented as

• The next edge is ( 2,5 ). When we find vertex 2 in an array, we observe that 1 is the parent of the
vertex 2 and the vertex 1 is the parent of itself. When we find 5 in an array, we find -2 value which
means vertex 5 is the parent of itself. Now we have to decide whether the vertex 1 or vertex 5
would become a parent. Since the weight of vertex 1, i.e., -4 is greater than the vertex of 5, i.e., -
2, so when we apply the union operation then the vertex 5 would become a child of the vertex 1
shown as below:

• In an array, 1 would be added at the index 5 as the vertex 1 is now becomes a parent of vertex 5.
We add -6 at the index 1 as two more nodes are added to the node 1.

• The next edge is (1,3). When we find vertex 1 in an array, we observe that 1 is the parent of itself.
When we find 3 in an array, we observe that 1 is the parent of vertex 3. Therefore, the parent of
both the vertices are same; so, we can say that there is a formation of cycle if we include the edge
(1,3).

• The next edge is (6,8). When we find vertex 6 in an array, we observe that vertex 5 is the parent
of vertex 6 and vertex 1 is the parent of vertex 5. When we find 8 in an array, we observe that
vertex 7 is the parent of the vertex 8 and 7 is the parent of itself. Since the weight of vertex 1, i.e.,

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 39 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

-6 is greater than the vertex 7, i.e., -2, so we make the vertex 7 as the child of the vertex and can
be represented graphically as shown as below:
• We add 1 at the index 7 because 7 becomes a child of the vertex 1. We add -8 at the index 1 as the
weight of the graph now becomes 8.

• The last edge to be included is (5, 7). When we find vertex 5 in an array, we observe that vertex 1
is the parent of the vertex 5. Similarly, when we find vertex 7 in an array, we observe that vertex
1 is the parent of vertex 7. Therefore, we can say that the parent of both the vertices is same, i.e.,
1. It means that the inclusion (5,7) edge would form a cycle.

• Till now, we have learnt the weighted union where we perform the union operation according to
the weights of the vertices. The higher weighted vertex becomes a parent and the lower weighted
vertex becomes a child. The disadvantage of using this approach is that some nodes take more time
to reach its parent. For example, in the above graph, if we want to find the parent of vertex 6,
vertex 5 is the parent of vertex 6 so we move to the vertex 5 and vertex 1 is the parent of the vertex
5. To overcome such problem, we use the concept 'collapsing find'.

How collapsing find technique works?


• Consider the above example. Once we know the parent of the vertex 6 which is 1 then we directly
add the vertex 6 to the vertex 1. We will also update the array. In an array, add 1 at the index 6
because the parent of 6 is now 1. The process of directly linking a node to the direct parent of a set
is known as a collapsing find. Similarly, we can link the nodes 8 and 4 to the node 1.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 40 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

4.6. Counting Binary Trees


• we wish to determine the number of distinct binary trees having n nodes, the number of distinct
permutations of the numbers from I to n obtainable by a stack, and the number of distinct ways of
multiplying n + 1 matrices.

4.6.1. Distinct Binary Trees


• We know that if n = 0 or n = 1, there is only one binary tree. If n = 2, then there are two distinct
trees and if n = 3, there are five such trees

Distinct binary trees with n = 2

Distinct binary trees with n = 3

4.6.2. Stack Permutations


• Refer Construction of binary tree given Pre order and inorder.

4.6.3. Number of Distinct Binary Trees


• To obtain the number of distinct binary trees with n nodes, In general
2𝑛𝑐𝑛
𝑛+1

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 41 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

4.7. Graphs: The Graph Abstract Data Types


4.7.1. Definition
• A Graph is a non-linear data structure consisting of vertices and edges.
• The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect
any two nodes in the graph.
• More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is
denoted by G(E, V).

4.7.2. Components of a Graph


• Vertices: Vertices are the fundamental units of the graph. Sometimes, vertices are also known as
vertex or nodes. Every node/vertex can be labeled or unlabelled.
• Edges: Edges are drawn or used to connect two nodes of the graph. It can be ordered pair of nodes
in a directed graph. Edges can connect any two nodes in any possible way. There are no rules.
Sometimes, edges are also known as arcs. Every edge can be labeled/unlabelled.

4.7.3. Applications of a Graph


• Social Networks
o Graphs represent relationships between users. Each user is a node, and each connection
(friendship, follow, etc.) is an edge.
o This helps in analyzing social structures, finding influencers, and recommending friends.
• Web Graphs
o The World Wide Web can be represented as a graph where web pages are nodes and
hyperlinks are edges.
o This is crucial for search engines to rank pages (e.g., Google's PageRank algorithm).
• Biological Networks
o Graphs model biological systems, such as protein-protein interaction networks, gene
regulatory networks, and metabolic pathways.
o This helps in understanding complex biological processes and disease mechanisms.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 42 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• Transportation Networks
o Graphs are used to model transportation systems, where intersections are nodes and roads
are edges.
o This is essential for route planning, traffic management, and logistics.
• Computer Networks
o In computer networks, devices are nodes and connections are edges.
o Graphs help in network design, analyzing connectivity, and optimizing data flow.
• Recommendation Systems
o Graphs are used to model user-item interactions.
o For example, in e-commerce, users and products are nodes, and purchases or ratings are
edges.
o This helps in recommending products to users based on their preferences.
• Project Management
o Graphs, specifically directed acyclic graphs (DAGs), are used in project management to
represent tasks and their dependencies.
o This helps in scheduling and resource allocation.
• Geographical Information Systems (GIS)
o Graphs model geographical data, where locations are nodes and paths are edges.
o This is used in mapping, navigation, and spatial analysis.
• Blockchain and Cryptocurrencies
o Graphs represent transactions in blockchain networks.
o Nodes are transactions, and edges represent the flow of currency.
o This helps in analyzing transaction patterns and ensuring security.
• Artificial Intelligence and Machine Learning
o Graphs are used in various AI and ML algorithms, such as graph neural networks (GNNs),
which are used for tasks like node classification, link prediction, and graph classification.
o Graphs are a powerful tool for modeling and solving complex problems in many domains

4.7.4. Terminologies
• Path: A path can be defined as the sequence of nodes that are followed in order to reach some
terminal node V from the initial node U.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 43 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• Closed Path: A path will be called as closed path if the initial node is same as terminal node. A
path will be closed path if V0=VN.
• Simple Path: If all the nodes of the graph are distinct with an exception V0=VN, then such path
P is called as closed simple path.
• Cycle: A cycle can be defined as the path which has no repeated edges or vertices except the first
and last vertices.
• Connected Graph: A connected graph is the one in which some path exists between every two
vertices (u, v) in V. There are no isolated nodes in connected graph.
• Complete Graph: A complete graph is the one in which every node is connected with all other
nodes. A complete graph contain n(n-1)/2 edges where n is the number of nodes in the graph.
• Weighted Graph: In a weighted graph, each edge is assigned with some data such as length or
weight. The weight of an edge e can be given as w(e) which must be a positive (+) value indicating
the cost of traversing the edge.
• Digraph: A digraph is a directed graph in which each edge of the graph is associated with some
direction and the traversing can be done only in the specified direction.
• Loop: An edge that is associated with the similar end points can be called as Loop.
• Adjacent Nodes: If two nodes u and v are connected via an edge e, then the nodes u and v are
called as neighbours or adjacent nodes.
• Degree of the Node: A degree of a node is the number of edges that are connected with that node.
A node with degree 0 is called as isolated node.

4.7.5. Tree vs Graph


basis of
Graph Tree
Comparison
Definition Graph is a non-linear data structure. Tree is a non-linear data structure.
It is a collection of vertices/nodes and
Structure It is a collection of nodes and edges.
edges.
A graph can be connected or A tree is a type of graph that is
disconnected, can have cycles or loops, connected, acyclic (meaning it has no
Structure cycle
and does not necessarily have a root cycles or loops), and has a single root
node. node.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 44 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Each node can have any number of If there is n nodes then there would be
Edges
edges. n-1 number of edges
Types of Edges They can be directed or undirected They are always directed
There is no unique node called root in There is a unique node called root(parent)
Root node
graph. node in trees.
Loop Formation A cycle can be formed. There will not be any cycle.
For graph traversal, we use Breadth-
We traverse a tree using in-order, pre-
Traversal First Search (BFS), and Depth-First
order, or post-order traversal methods.
Search (DFS).
For finding shortest path in networking For game trees, decision trees, the tree is
Applications
graph is used. used.
In a graph, nodes can have any number In a tree, each node (except the root node)
Node
of connections to other nodes, and there has a parent node and zero or more child
relationships
is no strict parent-child relationship. nodes.

Commonly used social networks, transportation file systems, organization charts, and
for networks, and computer networks. family trees.
In a tree, each node can have at most one
In a graph, nodes can have any number
Connectivity parent, except for the root node, which has
of connections to other nodes.
no parent.

4.7.6. Matrix and Adjacency List Representation of Graphs


• A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes
also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph.
• A graph can be represented in mainly two ways. They are:
o Adjacency Linked List
o Adjacency Matrix:

4.7.7. Adjacency Linked List


• An Adjacency list is an array consisting of the address of all the linked lists.
• The first node of the linked list represents the vertex and the remaining lists connected to this node
represents the vertices to which this node is connected.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 45 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• This representation can also be used to represent a weighted graph. The linked list can slightly be
changed to even store the weight of the edge.

4.7.8. Adjacency Matrix


• Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let
the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j.
• Adjacency matrix for undirected graph is always symmetric. Adjacency Matrix is also used to
represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with
weight w.
• Suppose G is a simple directed graph with m nodes, and suppose the nodes of G have been ordered
and are called v1, v2,…, vm. Then the adjacency matrix A = (aij) of the graph G is the m × m matrix
defined as follows:
1 𝑖𝑓 𝑣𝑖 𝑖𝑠 𝑎𝑑𝑗𝑎𝑐𝑒𝑛𝑡 𝑡𝑜 𝑣𝑗 𝑡ℎ𝑎𝑡 𝑖𝑠 𝑖𝑓 𝑡ℎ𝑒𝑟𝑒 𝑖𝑠 𝑎𝑛 𝑒𝑑𝑔𝑒 (𝑣𝑖 , 𝑣𝑗 )
𝑎𝑖𝑗 = {
0 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒
• In the adjacency matrix representation, a graph is represented in the form of a two-dimensional
array. The size of the array is V x V, where V is the set of vertices. The following image represents
the adjacency matrix representation:

Undirected Graph

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 46 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Directed Graph

4.7.9. Adjacency Matrix vs Adjacency List


Operations Adjacency Matrix Adjacency List
In the worst case, if a graph is connected O(V)
This representation makes use of VxV is required for a vertex and O(E) is required for
Storage
matrix, so space required in worst case storing neighbours corresponding to every
Space
is O(|V|2). vertex .Thus, overall space complexity is
O(|V|+|E|).
In order to add a new vertex to VxV
There are two pointers in adjacency list first
matrix the storage must be increases to
Adding a points to the front node and the other one
(|V|+1)2. To achieve this we need to
vertex points to the rear node.Thus insertion of a
copy the whole matrix. Therefore the
vertex can be done directly in O(1) time.
complexity is O(|V|2).
Similar to insertion of vertex here also two
To add an edge say from i to j,
Adding an pointers are used pointing to the rear and
matrix[i][j] = 1 which
edge front of the list. Thus, an edge can be
requires O(1) time.
inserted in O(1)time.
In order to remove a vertex, we need to
In order to remove a vertex from V*V
search for the vertex which will require
matrix the storage must be decreased to
Removing a O(|V|) time in worst case, after this we need
|V|2 from (|V|+1)2. To achieve this we
vertex to traverse the edges and in worst case it will
need to copy the whole matrix.
require O(|E|) time.Hence, total time
Therefore the complexity is O(|V|2).
complexity is O(|V|+|E|).
To remove an edge say from i to j, To remove an edge traversing through the edges
Removing
matrix[i][j] = 0 which is required and in worst case we need to traverse
an edge
requires O(1) time. through all the edges.Time complexity is O(|E|).

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 47 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

In an adjacency list every vertex is associated

In order to find for an existing edge the with a list of adjacent vertices. For a given
graph, in order to check for an edge we need to
content of matrix needs to be checked.
check for vertices adjacent to given vertex. A
Querying Given two vertices say i and j
vertex can have at most O(|V|) neighbours and in
matrix[i][j] can be checked
worst can we would have to check for every
in O(1) time.
adjacent vertex. Therefore, time complexity
is O(|V|) .

4.8. Traversal Methods: Breadth First Search and Depth FirstSearch.


4.8.1. Breadth First Search
• The breadth-first search (BFS) algorithm is used to search a tree or graph data structure for a node
that meets a set of criteria.
• It starts at the tree’s root or graph and searches/visits all nodes at the current depth level before
moving on to the nodes at the next depth level.
• Breadth-first search can be used to solve many problems in graph theory.
• To avoid processing a node more than once, we divide the vertices into two categories:
o Visited and
o Not visited.
• A boolean visited array is used to mark the visited vertices. For simplicity, it is assumed that all
vertices are reachable from the starting vertex. BFS uses a queue data structure for traversal.
• It is convenient to use a queue to trace the operation of breadth-first search. The queue is initialized
with the traversal's starting vertex, which is marked as visited.
• On each iteration, the algorithm identifies all unvisited vertices that are adjacent to the front vertex,
marks them as visited, and adds them to the queue; after that, the front vertex is removed from the
queue.
• Two different types of edges that are encountered during BFS traversal.
o Tree edge
o Cross edge
• Tree edge: During traversal, whenever a new unvisited vertex (v) is reached for the first time from
a current vertex (u), then the edge (u, v) is called a tree edge.
The tree edges are represented using solid edges.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 48 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• Cross edge : During traversal, whenever an already visited vertex (v) is visited from the current
vertex (u) and v is not a immediate predecessor of u , then the edge (u, v) is called a cross edge.
The cross edges are represented using dotted lines.

• Example:

• In the above graph, we start traversal from vertex 2.


• When we come to vertex 0, we look for all adjacent vertices of it.
o 2 is also an adjacent vertex of 0.
o If we don’t mark visited vertices, then 2 will be processed again and it will become a non-
terminating process.
• Procedure for BFS
Step 1: Initialize Queue with start vertex and mark this vertex as visited.
Step2 : While Queue is not Empty
Delete a vertex ‘u’ from Queue
Identify all the vertices ‘v’ adjacent to ‘u’
If the vertices adjacent to ‘u’ are not visited
Mark them as visited
Insert all marked items into Queue
Output u, v
End if
End while

Step 3: Repeat step1 and step 2 until all vertices in the graph are considered
Illustration

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 49 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• Example 2:

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 50 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

4.8.2. Depth First Search


• Depth first Search is a recursive algorithm for searching all the vertices of a graph or tree data
structure. Traversal means visiting all the nodes of a graph.
• In DFS, a vertex u is picked as source vertex and is visited. The vertex u at this point is said to be
unexplored. The exploration of the vertex u is postponed and vertex v adjacent to u is picked and
is visited.
• The search begins at the vertex v. there may be still some nodes which are adjacent to u but not
visited. When the vertex v is completely examined, then only u is examined.
• The search will terminate when all the vertices have been examined.

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 51 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

• It is convenient to use a stack to trace the operation of depth-first search. We push a vertex onto
the stack when the vertex is reached for the first time (i.e., the visit of the vertex starts), and we
pop a vertex off the stack when it becomes a dead end (i.e., the visit of the vertex ends).
• Two different types of edges that are encountered during BFS traversal.
o Tree edge
o Back edge
• Tree edge: During traversal, whenever a new unvisited vertex (v) is reached for the first time from
a current vertex (u), then the edge (u, v) is called a tree edge.
The tree edges are represented using solid edges.
• Back edge: During traversal, whenever an already visited vertex (v) is visited from the current
vertex (u) and v is not an immediate predecessor of u , then the edge (u, v) is called a cross edge.
The cross edges are represented using dotted lines.

• DFS yields two ordering of vertices:


o The order in which vertices are reached for the first time. When a vertex is reached for the
first time it is pushed onto the stack and each vertex is numbered in the order in which it is
pushed onto the stack.
o The order in which the vertices become dead ends. When a vertex is dead end( when all
the adjacent vertices are explored), it is removed from the stack. Each node is numbered in
the order in which it is deleted from the stack.

• Procedure
Step 1: Select node ‘u’ as the start vertex, push ‘u’ onto stack and mark as visited. Add
‘u’ to ‘S’ for marking.
Step 2: while stack is not empty
For vertex ‘u’ on top of the stack, find the next immediate adjacent vertex
If ‘v’ is adjacent
If a vertex ‘v’ is not visted the
Push ‘v’ into stack and number it in the order it is pushed
Mark it as visited by adding ‘v’ to S
Else
Ignore the vertex

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 52 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

End if
Else
Remove the vertex from stack
Number it in the order it is popped
End if
Step 3: Repeat step1 and step2 until all vertices in the graph are considered

• Example

Comparison, Similarities and Applications of BFS and DFS traversals

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 53 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

SL
BFS DFS
No.
Comparison
1 The data structure used is QUEUE The data structure used is STACK
1 vertex ordering is used, as the order in 2 vertex ordering is used, as the order in which
2 which items are inserted is same as the items are inserted is different from the order in
order in which items are deleted which items are deleted
The exploration of node is postponed as soon as
A node is fully explored before the a new unexplored node is reached and
3
exploration of any other node begins. examination of the new node begins
immediately.
4 Tree edges and Cross edges are present Tree edges and Back edges are present

Similarities

Used to check for connectivity and Used to check for connectivity and acyclicity of a
1
acyclicity of a graph. graph.
Time efficiency using adjacency matrix Time efficiency using adjacency matrix
2
𝜽(|𝒗|𝟐) 𝜽(|𝒗|𝟐)
Time efficiency using Linked list Time efficiency using Linked list
3
𝜽(𝑽+𝑬) 𝜽(𝑽+𝑬)

Applications

1 Used to check connectivity of the graph. Used to check connectivity of the graph.
Used to check whether the graph is
2 Used to check whether the graph is acyclic or not
acyclic or not
3 To find the spanning tree To find the spanning tree
Used to find the path with fewest number Solving puzzles with only one solution, such as
4
of edges. mazes
5 Topological sorting

• C Program to traverse the graph using BFS and DFS method


#include<stdio.h>

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 54 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

#include<stdlib.h>
int a[10][10], n, m, i, j, source, s[10], q[10];
int visited[10];
void create()
{
printf("\nEnter the number of vertices of the digraph: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix of the graph:\n");
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
scanf("%d",&a[i][j]);
}

void bfs(int source) {


int u, front=0, rear=-1;
q[++rear] = source;
visited[source] = 1;
printf("\nThe reachable vertices are: ");
printf("%d\t", source);
while(front<=rear) {
u = q[front++];
for(i=1; i<=n; i++)
{
if(a[u][i] == 1 && visited[i] == 0)
{
q[++rear] = i;
visited[i] = 1;
printf("%d\t", i);
}
}
}
}

void dfs(int source)

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 55 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

{
int v, top = -1;
s[source] = 1;
for(v=1; v<=n; v++)
{
if(a[source][v] == 1 && s[v] == 0)
{
printf("\n%d -> %d", source, v);
dfs(v);
}
}
}

void main() {
int ch;
while(1)
{
printf("\n------------- GRAPH TRAVERSALS ---------------");
printf("\n1.Create Graph\n 2.BFS\n 3. DFS\n 4.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
create();
break;
case 2:
printf("\nEnter the source vertex to find other nodes reachable or not: ");
scanf("%d", &source);
bfs(source);
for(i=1; i<=n; i++)
if(visited[i]==0)
printf("\nThe vertex that is not reachable %d",i);

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 56 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

break;
case 3:
printf("\nEnter the source vertex to find the connectivity: ");
scanf("%d",&source);
m=1;
dfs(source);
for(i=1; i<=n; i++)
{
if(s[i]==0)
m=0;
}
if(m==1)
printf("\nGraph is Connected");
else
printf("\nGraph is not Connected");
break;
default:
exit(0);
}
}
}

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 57 of 58


Data Structures and Applications (BCS304) Module 4: Trees & Graphs

Department of AI&ML, Vemana IT Prepared by: Dr. Kantharaju H C Page 58 of 58

You might also like