BCS304 DS Module 4 Notes
BCS304 DS Module 4 Notes
Module 4
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.
Basic Operations
• Insertion: Inserts an element in a tree.
• Traversal
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 60
• As 60 > 50, so insert 60 to the right of 50.
• As 60 < 70, so insert 60 to the left of 70.
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.
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.
• 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.
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;
if number == root->data
return root->data;
if number < root->data
return search(root->left)
if number > root->data
return search(root->right)
• Representation
// 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
}
}
return node;
}
//Search
// 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;
}
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);
}
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;
Btree pop() {
return (stack[stackPtr--]);
}
}
void operatorFunc(char var) {
Btree root = (Btree)malloc(sizeof(struct node));
root->item = var;
root->right = pop();
root->left = pop();
push(root);
}
case '$':
case '%': return 0;
default: return 1;
}
}
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');
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]);
}
}
• 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)
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)
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.
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
• 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.
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)
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:
• 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
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.
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
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
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
• 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
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
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}
• 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.
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}
• 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}
• 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.
First, we consider the vertices 1 and 2, i.e., (1, 2) and represent them through graphically shown
as below:
• 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.
• 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.
• 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:
• 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.,
-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'.
• 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.
• 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.
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.
• 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.
Undirected Graph
Directed Graph
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|) .
• 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:
Step 3: Repeat step1 and step 2 until all vertices in the graph are considered
Illustration
• Example 2:
• 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.
• 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
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
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
#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]);
}
{
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);
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);
}
}
}