DS_Tree_Notes
DS_Tree_Notes
Linked List:
A linked list is a linear data structure which can store a collection of "nodes"
connected together via links i.e. pointers. Linked lists nodes are not stored at a
contiguous location, rather they are linked using pointers to the different
memory locations. A node consists of the data value and a pointer to the
address of the next node within the linked list.
A linked list is a dynamic linear data structure whose memory size can be
allocated or de-allocated at run time based on the operation insertion or
deletion, this helps in using system memory efficiently. Linked lists can be used
to implement various data structures like a stack, queue, graph, hash maps,
etc.
A linked list starts with a head node which points to the first node. Every node
consists of data which holds the actual data (value) associated with the node
and a next pointer which holds the memory address of the next node in the
linked list. The last node is called the tail node in the list which points
to null indicating the end of the list.
Why use linked list over array?
Linked list is a data structure that overcomes the limitations of arrays. Let's first
see some of the limitations of arrays -
The size of the array must be known in advance before using it in the
program.
Increasing the size of the array is a time taking process. It is almost
impossible to expand the size of the array at run time.
All the elements in the array need to be contiguously stored in the
memory. Inserting an element in the array needs shifting of all its
predecessors.
Linked list is useful because -
It allocates the memory dynamically. All the nodes of the linked list are
non-contiguously stored in the memory and linked together with the help
of pointers.
In linked list, size is no longer a problem since we do not need to define its
size at the time of declaration. List grows as per the program's demand
and limited to the available memory space.
Declaring a Linked List
It is simple to declare an array, as it is of single type, while the declaration of
linked list is a bit more typical than array. Linked list contains two parts, and
both are of different types, i.e., one is the simple variable, while another is the
pointer variable. We can declare the linked list by using the user-defined data
type structure.
The declaration of linked list is given as follows -
Page | 1
2|Page
struct node
{
int data;
struct node *next;
}
In the above declaration, we have defined a structure named as node that
contains two variables, one is data that is of integer type, and another one
is next that is a pointer which contains the address of next node.
We can observe in the above figure that there are three different nodes having address 100, 200 and 300
respectively. The first node contains the address of the next node, i.e., 200, the second node contains the address of
the last node, i.e., 300, and the third node contains the NULL value in its address part as it does not point to any
node. The pointer that holds the address of the initial node is known as a head pointer.
The linked list, which is shown in the above diagram, is known as a singly linked list as it contains only a single link. In
this list, only forward traversal is possible; we cannot traverse in the backward direction as it has only one link in the
list.
Representation of the node in a singly linked list
struct node
{
int data;
struct node *next;
}
In the above representation, we have defined a user-defined structure named a node containing two members, the
first one is data of integer type, and the other one is the pointer (next) of the node type.
Doubly linked list
As the name suggests, the doubly linked list contains two pointers. We can define the doubly linked list as a linear
data structure with three parts: the data part and the other two address part. In other words, a doubly linked list is a
list that has three parts in a single node, includes one data part, a pointer to its previous node, and a pointer to the
next node.
Suppose we have three nodes, and the address of these nodes are 100, 200 and 300, respectively. The
representation of these nodes in a doubly-linked list is shown below:
Page | 2
3|Page
As we can observe in the above figure, the node in a doubly-linked list has two address parts; one part stores
the address of the next while the other part of the node stores the previous node's address. The initial node in the
doubly linked list has the NULL value in the address part, which provides the address of the previous node.
Page | 3
4|Page
The above figure shows the representation of the doubly circular linked list in which the last node is attached to the
first node and thus creates a circle. It is a doubly linked list also because each node holds the address of the previous
node also. The main difference between the doubly linked list and doubly circular linked list is that the doubly
circular linked list does not contain the NULL value in the previous field of the node. As the doubly circular linked
contains three parts, i.e., two address parts and one data part so its representation is similar to the doubly linked list.
struct node
{
int data;
struct node *next;
struct node *prev;
}
Advantages of linked lists
1) The primary advantage of linked list over arrays is that linked list can
increase and decrease in size. That means their maximum size need not be
mentioned in advance. This is a very good advantage in practical applications.
2) The second advantage of linked list is the flexibility in allowing the items to
the rearranged efficiently. This flexibility is gained at the experience of quick
access to any item in this.
3) The insertion and deletion of an element takes one time. Unlike array
implementation in which they take n-times.
Limitations of linked lists:
1) The space needed to store a list using more.
2) Another limitation is that it is not possible to travel a list in both directions.
This can be overcome in double linked list.
Differences between arrays & linked lists:
Arrays Linked List
1. Array is fixed in size. 1. No. of nodes in the list is unlimited.
2. Static allocation of memory is 2. Dynamic Memory allocation is done.
done.
3. Use initialized area. 3. Uses free store or heap memory
area.
4. Only identical items can be placed. 4. Identical or different items may be
placed.
5. Optimum utilization of memory will 5. Optimum utilization of memory is
not be found. done.
6. Do not use pointers concept. 6. Uses pointers only.
7. Continuous blocks of memory is 7. Doesn’t need continuous memory.
Page | 4
5|Page
required.
BASIC OPERATIONS ON SINGLE LINKED LISTS
Creating a Linked List:
The creation of a list is the most basic operation among other operations.
Algorithm: Creation( )
[ Initially head = null and last = null ]
Step-1: Read a value into item
Step-2: if(item = = -1) then
[ end the process ]
Else
Step-2.1 :
create a new node called “temp”
Step-2.2 : Insert temp.data = item , temp.link = null.
Step-2.3 : if head = = null then
head = last = temp
else
last.link = temp
last = temp
[ Repeat the process until item = -1 ]
Step-3: Exit
Insertion
In a single linked list, the insertion operation can be performed in three ways.
They are as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of the single
linked list...
Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then,
set newNode→next = NULL and head = newNode.
Step 4 - If it is Not Empty then,
set newNode→next = head and head = newNode.
void insertAtBeginning(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(head == NULL)
{
newNode->next = NULL;
head = newNode;
}
else
{
newNode->next = head;
head = newNode;
Page | 5
6|Page
}
printf("\nOne node inserted!!!\n");
}
Inserting At End of the list
We can use the following steps to insert a new node at end of the single linked
list...
Step 1 - Create a newNode with given value and newNode →
next as NULL.
Step 2 - Check whether list is Empty (head == NULL).
Step 3 - If it is Empty then, set head = newNode.
Step 4 - If it is Not Empty then, define a node pointer temp and
initialize with head.
Step 5 - Keep moving the temp to its next node until it reaches to the
last node in the list (until temp → next is equal to NULL).
Step 6 - Set temp → next = newNode.
void insertAtEnd(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if(head == NULL)
head = newNode;
else
{
struct Node *temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
printf("\nOne node inserted!!!\n");
}
Inserting At Specific location in the list (After a Node)
We can use the following steps to insert a new node after a node in the single
linked list...
Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, set newNode →
next = NULL and head = newNode.
Step 4 - If it is Not Empty then, define a node pointer temp and
initialize with head.
Step 5 - Keep moving the temp to its next node until it reaches to the
node after which we want to insert the newNode (until temp1 → data is
equal to location, here location is the node value after which we want to
insert the newNode).
Step 6 - Every time check whether temp is reached to last node or not. If
it is reached to last node then display 'Given node is not found in the
list!!! Insertion not possible!!!' and terminate the function. Otherwise
move the temp to next node.
Step 7 - Finally, Set 'newNode → next = temp → next' and 'temp →
next = newNode'
void insertBetween(int value, int loc1, int loc2)
{
Page | 6
7|Page
temp = temp->next;
}
printf("%d --->NULL",temp->data);
}
}
Operations
In a circular linked list, we perform the following operations...
1. Insertion
2. Deletion
3. Display
Before we implement actual operations, first we need to setup empty list. First
perform the following steps before implementing actual operations.
Step 1 - Include all the header files which are used in the program.
Step 2 - Declare all the user defined functions.
Step 3 - Define a Node structure with two members data and next
Step 4 - Define a Node pointer 'head' and set it to NULL.
Step 5 - Implement the main method by displaying operations menu and
make suitable function calls in the main method to perform user selected
operation.
Insertion
In a circular linked list, the insertion operation can be performed in three ways.
They are as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of the circular
linked list...
Step 1 - Create a newNode with given value.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then,
set head = newNode and newNode→next = head .
Page | 11
12 | P a g e
Step 7 - If list has only one node and that is the node to be deleted then
set head = NULL and delete temp1 (free(temp1)).
Step 8 - If list contains multiple nodes then check whether temp1 is the
first node in the list (temp1 == head).
Step 9 - If temp1 is the first node then set temp2 = head and keep
moving temp2 to its next node until temp2 reaches to the last node.
Then set head = head → next, temp2 → next = head and
delete temp1.
Step 10 - If temp1 is not first node then check whether it is last node in
the list (temp1 → next == head).
Step 1 1- If temp1 is last node then set temp2 → next = head and
delete temp1 (free(temp1)).
Step 12 - If temp1 is not first node and not last node then set temp2 →
next = temp1 → next and delete temp1(free(temp1)).
Displaying a circular Linked List
We can use the following steps to display the elements of a circular linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the
function.
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and
initialize with head.
Step 4 - Keep displaying temp → data with an arrow (--->)
until temp reaches to the last node
Step 5 - Finally display temp → data with arrow pointing to head →
data.
Double Linked List
What is Double Linked List?
In a single linked list, every node has link to its next node in the sequence. So,
we can traverse from one node to other node only in one direction and we can
not traverse back. We can solve this kind of problem by using double linked list.
Double linked list can be defined as follows...
Double linked list is a sequence of elements in which every element
has links to its previous element and next element in the sequence.
In double linked list, every node has link to its previous node and next node. So,
we can traverse forward by using next field and can traverse backward by
using previous field. Every node in a double linked list contains three fields and
they are shown in the following figure...
Here, 'link1' field is used to store the address of the previous node in the
sequence, 'link2' field is used to store the address of the next node in the
sequence and 'data' field is used to store the actual value of that node.
Example
Page | 14
15 | P a g e
Page | 15
16 | P a g e
Page | 16
17 | P a g e
Step 5 - If it is TRUE, then assign NULL to head and delete temp. And
terminate from the function. (Setting Empty list condition)
Step 6 - If it is FALSE, then keep moving temp until it reaches to the last
node in the list. (until temp → next is equal to NULL)
Step 7 - Assign NULL to temp → previous → next and delete temp.
Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the double linked
list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
Step 3 - If it is not Empty, then define a Node pointer 'temp' and
initialize with head.
Step 4 - Keep moving the temp until it reaches to the exact node to be
deleted or to the last node.
Step 5 - If it is reached to the last node, then display 'Given node not
found in the list! Deletion not possible!!!' and terminate the fuction.
Step 6 - If it is reached to the exact node which we want to delete, then
check whether list is having only one node or not
Step 7 - If list has only one node and that is the node which is to be
deleted then set head to NULL and delete temp(free(temp)).
Step 8 - If list contains multiple nodes, then check whether temp is the
first node in the list (temp == head).
Step 9 - If temp is the first node, then move the head to the next node
(head = head → next), set head of previous to NULL (head →
previous = NULL) and delete temp.
Step 10 - If temp is not the first node, then check whether it is the last
node in the list (temp → next == NULL).
Step 11 - If temp is the last node then
set temp of previous of next to NULL (temp → previous → next =
NULL) and delete temp (free(temp)).
Step 12 - If temp is not the first node and not the last node, then
set temp of previous of next to temp of next (temp → previous →
next = temp →
next), temp of next of previous to temp of previous (temp → next →
previous = temp → previous) and delete temp (free(temp)).
Displaying a Double Linked List
We can use the following steps to display the elements of a double linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the
function.
Step 3 - If it is not Empty, then define a Node pointer 'temp' and
initialize with head.
Step 4 - Display 'NULL <--- '.
Step 5 - Keep displaying temp → data with an arrow (<===>)
until temp reaches to the last node
Step 6 - Finally, display temp → data with arrow pointing
to NULL (temp → data ---> NULL).
Page | 17
18 | P a g e
Example:
Imagine a circular doubly linked list like a Ferris wheel. Each node is like a seat
on the Ferris wheel. You can move to the seat next to you (forward) or the seat
behind you (backward). And when you reach the last seat, instead of stopping,
you move to the first seat again, just like how the Ferris wheel goes round and
round.
This structure is useful in many computer applications where you need to cycle
through data repeatedly, such as in task scheduling or managing playlists in a
media player.
Page | 18
19 | P a g e
Page | 19
20 | P a g e
Terminology
In a tree data structure, we use
the following terminology...
1. Root
In a tree data structure, the first
node is called as Root Node.
Every tree must have root node. We can say that root node is the origin of tree
data structure. In any tree, there must be only one root node. We never have
multiple root nodes in a tree.
2. Edge
In a tree data structure, the
connecting link between any
two nodes is called as EDGE.
In a tree with 'N' number of
nodes there will be a
maximum of 'N-1' number of
edges.
3. Parent
In a tree data structure, the
node which is predecessor of
any node is called
as PARENT NODE. In simple
words, the node which has
branch from it to any other
node is called as parent
Page | 20
21 | P a g e
node. Parent node can also be defined as "The node which has child /
children".
4. Child
In a tree data structure, the
node which is descendant of
any node is called as CHILD
Node. In simple words, the
node which has a link from
its parent node is called as
child node. In a tree, any
parent node can have any
number of child nodes. In a
tree, all the nodes except root are child nodes.
5. Siblings
In a tree data structure,
nodes which belong to same
Parent are called
as SIBLINGS. In simple
words, the nodes with same
parent are called as Sibling
nodes.
6. Leaf
In a tree data structure, the
node which does not have a
child is called as LEAF
Node. In simple words, a
leaf is a node with no child.
7. Internal Nodes
In a tree data structure, the
node which has atleast one
child is called as INTERNAL
Node. In simple words, an
internal node is a node with
atleast one child.
nodes other than leaf nodes are called as Internal Nodes. The root node is
also said to be Internal Node if the tree has more than one node. Internal
nodes are also called as 'Non-Terminal' nodes.
8. Degree
In a tree data structure, the
total number of children of a
node is called as DEGREE of
that Node. In simple words,
the Degree of a node is total
number of children it has.
The highest degree of a node
among all the nodes in a tree
is called as 'Degree of Tree'
9. Level
In a tree data structure, the
root node is said to be at
Level 0 and the children of
root node are at Level 1 and
the children of the nodes
which are at Level 1 will be
at Level 2 and so on... In
simple words, in a tree each
step from top to bottom is
called as a Level and the
Level count starts with '0' and
incremented by one at each
level (Step).
10. Height
In a tree data structure, the total number of edges from leaf node to a
particular node in the longest path is called as HEIGHT of that Node. In a tree,
height of the root node is said to be height of the tree. In a tree, height of
all leaf nodes is '0'.
11. Depth
In a tree data structure, the
total number of egdes from
root node to a particular node is
called as DEPTH of that
Node. In a tree, the total
number of edges from root
node to a leaf node in the longest path is said to be Depth of the tree. In
Page | 22
23 | P a g e
simple words, the highest depth of any leaf node in a tree is said to be depth of
that tree. In a tree, depth of the root node is '0'.
12. Path
In a tree data structure, the
sequence of Nodes and Edges
from one node to another
node is called
as PATH between that two
Nodes. Length of a Path is
total number of nodes in that
path. In below example the path A - B - E - J has length 4.
Tree Representations
A tree data structure can be represented in two methods. Those methods are
as follows...
1. Linked List Representation
2. Left Child - Right Sibling Representation
1. List Representation
In this representation, we use
two types of nodes one for
representing the node with
data called 'data node' and
another for representing only
references called 'reference
node'. We start with a 'data
node' from root node in the
tree. Then it is linked to an internal node through a 'reference node' which is
further linked to any other node directly. This process repeats for all the nodes
in the tree.
The above example tree can be represented using List representation as
follows...
consists of three fields namely Data field, Left child reference field and Right
sibling reference field. Data field stores the actual value of a node, left
reference field stores the address of the left child and right reference field
stores the address of the right sibling node. Graphical representation of that
node is as follows...
In this
representation,
every node's
data field stores
the actual value of
that node. If that
node has left
child, then left
reference field
stores the
address of that
left child node
otherwise stores
NULL. If that
node has right sibling, then right reference field stores the address of right
sibling node otherwise stores NULL.
The above example tree can be represented using Left Child - Right Sibling
representation as in the figure...
Binary Tree Data structure
In a normal tree, every node can
have any number of children.
Binary tree is a special type of
tree data structure in which every
node can have a maximum of 2
children. One is known as left
child and the other is known as
right child.
A tree in which every node can
have a maximum of two children is
called as Binary Tree.
In a binary tree, every node can have either 0 children or 1 child or 2 children
but not more than 2
children.
Example
In a binary tree, every node can have a maximum of two children. But in strictly
binary tree, every node should have exactly two children or none. That means
every internal node must have exactly two children. A strictly Binary Tree can
be defined as follows...
A binary tree in which every node has either two or zero number of children is
called Strictly Binary Tree
Strictly binary tree is also called as Full Binary Tree or Proper Binary
Tree or 2-Tree
Strictly binary tree data structure is used to represent mathematical
expressions.
Example
3.
Extended
Binary
Tree
A binary
tree can be
converted
Page | 25
26 | P a g e
into Full Binary tree by adding dummy nodes to existing nodes wherever
required.
The full binary tree obtained by adding dummy nodes to a binary tree is called
as Extended Binary Tree.
To represent a binary tree of depth 'n' using array representation, we need one
dimensional array with a maximum size of 2n + 1.
2. Linked List Representation of Binary Tree
We use double linked list to represent a binary tree. In a double linked list,
every node consists of three fields. First field for storing left child address,
second for storing actual data and third for storing right child address.
In this linked list representation, a node has the following structure...
The above example of binary tree represented using Linked list representation
is shown as follows...
Page | 26
27 | P a g e
Page | 27
28 | P a g e
Introduction to Graphs
Graph is a non linear data structure. It contains set of points known as nodes
(or vertices) and set of links known as edges (or Arcs). Here edges are used to
connect the vertices. A graph is defined as follows...
Graph is a collection of vertices and arcs in which vertices are connected with
arcs
Graph is a collection of nodes and edges in which nodes are connected with
edges
Generally, a graph G is represented as G = ( V , E ), where V is set of
vertices and E is set of edges.
Example
The following is a graph with 5 vertices and 6 edges.
This graph G can be defined as G = ( V , E )
Where V = {A,B,C,D,E} and E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}.
Graph Terminology
We use the following terms in graph data structure...
Vertex
Individual data element of a graph is called as Vertex. Vertex is also known
as node. In above example graph, A, B, C, D & E are known as vertices.
Edge
An edge is a connecting link between two vertices. Edge is also known as Arc.
An edge is represented as (startingVertex, endingVertex). For example, in
above graph the link between vertices A and B is represented as (A,B). In above
example graph, there are 7 edges (i.e., (A,B), (A,C), (A,D), (B,D), (B,E), (C,D),
(D,E)).
Page | 28
29 | P a g e
A graph with both undirected and directed edges is said to be mixed graph.
End vertices or Endpoints
The two vertices joined by edge are called end vertices (or endpoints) of that
edge.
Origin
If a edge is directed, its first endpoint is said to be the origin of it.
Destination
If a edge is directed, its first endpoint is said to be the origin of it and the other
endpoint is said to be the destination of that edge.
Adjacent
If there is a edge between vertices A and B then both A and B are said to be
adjacent. In other words, vertices A and B are said to be adjacent if there is a
edge between them.
Incident
Edge is said to be incident on a vertex if the vertex is one of the endpoints of
that edge.
Outgoing Edge
A directed edge is said to be outgoing edge on its origin vertex.
Incoming Edge
A directed edge is said to be incoming edge on its destination vertex.
Degree
Total number of edges connected to a vertex is said to be degree of that
vertex.
Indegree
Total number of incoming edges connected to a vertex is said to be indegree of
that vertex.
Outdegree
Total number of outgoing edges connected to a vertex is said to be outdegree
of that vertex.
Parallel edges or Multiple edges
If there are two undirected edges with same end vertices and two directed
edges with same origin and destination, such edges are called parallel edges or
multiple edges.
Self-loop
Edge (undirected or directed) is a self-loop if its two endpoints coincide with
each other.
Simple Graph
A graph is said to be simple if there are no parallel and self-loop edges.
Path
A path is a sequence of alternate vertices and edges that starts at a vertex and
ends at other vertex such that each edge is incident to its predecessor and
successor vertex.
Graph Representations
Graph data structure is represented using following representations...
1. Adjacency Matrix
2. Incidence Matrix
3. Adjacency List
Adjacency Matrix
Page | 29
30 | P a g e
Incidence Matrix
In this representation, graph is represented using a matrix of size total number
of vertices by total number of edges. That means graph with 4 vertices and 6
edges is represented using a matrix of size 4X6. In this matrix, rows represents
vertices and columns represents edges. This matrix is filled with 0 or 1 or -1.
Here, 0 represents that the row edge is not connected to column vertex, 1
represents that the row edge is connected as outgoing edge to column vertex
and -1 represents that the row edge is connected as incoming edge to column
vertex.
Page | 30
31 | P a g e
Adjacency List
In this representation, every vertex of a graph contains list of its adjacent
vertices.
Page | 32
33 | P a g e
Empty, then produce final spanning tree by removing unused edges from
the graph
Back tracking is coming back to the vertex from which we reached the
current vertex.
Example
Page | 33
34 | P a g e
Page | 34
35 | P a g e
Graph traversal is a technique used for searching vertex in a graph. The graph
traversal is also used to decide the order of vertices to be visited in the search
process. A graph traversal finds the egdes to be used in the search process
without creating loops. That means using graph traversal we visit all the
vertices of graph without getting into looping path.
There are two graph traversal techniques and they are as follows...
Page | 35
36 | P a g e
Example
Page | 36
37 | P a g e
Page | 37
38 | P a g e
What is Graph?
Graph is an abstract data type.
It is a pictorial representation of a set of objects where some pairs of
objects are connected by links.
Graph is used to implement the undirected graph and directed graph
concepts from mathematics.
It represents much real life application. Graphs are used to represent
the networks. Network includes path in a city, telephone network etc.
It is used in social networks like Facebook, LinkedIn etc.
Graph consists of two following components:
1. Vertices
2. Edges
Graph is a set of vertices (V) and set of edges (E).
V is a finite number of vertices also called as nodes.
E is a set of ordered pair of vertices representing edges.
For Example On facebook, everything is a node. That includes User,
Photo, Album, Event, Group, Page, Comment, Story, Video, Link,
Note...anything that has data is a node.
Every relationship is an edge from one node to another. Whether you
post a photo, join a group, like a page etc., a new edge is created for
that relationship.
The above figures represent the graphs. The set representation for each of
these graphs are as follows:
Graph 1:
V = {A, B, C, D, E, F}
E = {(A, B), (A, C), (B, C), (B, D), (D, E), (D, F), (E, F)}
Graph 2:
V = {A, B, C, D, E, F}
E = {(A, B), (A, C), (B, D), (C, E), (C, F)}
Graph 3:
V = {A, B, C}
E = {(A, B), (A, C), (C, B)}
Directed Graph
If a graph contains ordered pair of vertices, is said to be a Directed
Graph.
Page | 38
39 | P a g e
Page | 39
40 | P a g e
The above graph represents directed graph with the adjacency matrix
representation. It shows adjacency matrix of directed graph which is
never symmetric. If there is an edge (2, 4), there is not an edge (4, 2). It
indicates direct edge from vertex i to vertex j.
Advantages of Adjacency Matrix
Adjacency matrix representation of graph is very simple to implement.
Adding or removing time of an edge can be done in O(1) time. Same
time is required to check, if there is an edge between two vertices.
It is very convenient and simple to program.
Disadvantages of Adjacency Matrix
It consumes huge amount of memory for storing big graphs.
It requires huge efforts for adding or removing a vertex. If you are
constructing a graph in dynamic structure, adjacency matrix is quite
slow for big graphs.
Adjacency List
Adjacency list is another representation of graphs.
It is a collection of unordered list, used to represent a finite graphs.
Page | 40
41 | P a g e
As stated before, in DFS, nodes are visited by going through the depth of
the tree from the starting node. If we do the depth first traversal of the
above graph and print the visited node, it will be “A B E F C D”. DFS visits
the root node and then its children nodes until it reaches the end node, i.e.
E and F nodes, then moves up to the parent nodes.
Algorithmic Steps
Step 1: Push the root node in the Stack.
Step 2: Loop until stack is empty.
Step 3: Peek the node of the stack.
Step 4: If the node has unvisited child nodes, get the unvisited child node, mark it as
traversed and push it on stack.
Step 5: If the node does not have any unvisited child nodes, pop the node from the stack.
Page | 42
43 | P a g e
We start from vertex 0, the DFS algorithm starts by putting it in the Visited
list and putting all its adjacent vertices in the stack.
Next, we visit the element at the top of stack i.e. 1 and go to its adjacent
nodes. Since 0 has already been visited, we visit 2 instead.
Page | 43
44 | P a g e
After we visit the last element 3, it doesn't have any unvisited adjacent
nodes, so we have completed the Depth First Traversal of the graph.
We start from vertex 0, the BFS algorithm starts by putting it in the Visited
list and putting all its adjacent vertices in the stack.
Next, we visit the element at the front of queue i.e. 1 and go to its adjacent
nodes. Since 0 has already been visited, we visit 2 instead.
Page | 45
46 | P a g e
Only 4 remains in the queue since the only adjacent node of 3 i.e. 0 is
already visited. We visit it.
Since the queue is empty, we have completed the Depth First Traversal of
the graph.
Spanning Tree and Minimum Spanning Tree
Spanning tree
A spanning tree is a sub-graph of an undirected and a connected graph,
which includes all the vertices of the graph having a minimum possible
number of edges. If a vertex is missed, then it is not a spanning tree.
The edges may or may not have weights assigned to them.
The total number of spanning trees with n vertices that can be created
from a complete graph is equal to n(n-2).
Example of a Spanning Tree
Let the original graph be:
Some of the possible spanning trees that can be created from the above
graph are:
Page | 46
47 | P a g e
The minimum spanning tree from the above spanning trees is:
Page | 47
48 | P a g e
The minimum spanning tree from a graph is found using the following
algorithms:
Prim's Algorithm
Kruskal's Algorithm
Prim's Algorithm
Prim's algorithm is a minimum spanning tree algorithm that takes a graph
as input and finds the subset of the edges of that graph which
form a tree that includes every vertex
has the minimum sum of weights among all the trees that can be formed
from the graph
How Prim's algorithm works
It falls under a class of algorithms called greedy algorithms which find the
local optimum in the hopes of finding a global optimum.
We start from one vertex and keep adding edges with the lowest weight
until we we reach our goal.
The steps for implementing Prim's algorithm are as follows:
Initialize the minimum spanning tree with a vertex chosen at random.
Find all the edges that connect the tree to new vertices, find the
minimum and add it to the tree
Keep repeating step 2 until we get a minimum spanning tree
Example of Prim's algorithm
Page | 48
49 | P a g e
Kruskal's Algorithm
Kruskal's algorithm is a minimum spanning tree algorithm that takes a graph as
input and finds the subset of the edges of that graph which
form a tree that includes every vertex
Page | 49
50 | P a g e
has the minimum sum of weights among all the trees that can be formed
from the graph
How Kruskal's algorithm works
It falls under a class of algorithms called greedy algorithms which find the local
optimum in the hopes of finding a global optimum.
We start from the edges with the lowest weight and keep adding edges
until we we reach our goal.
The steps for implementing Kruskal's algorithm are as follows:
Sort all the edges from low weight to high
Take the edge with the lowest weight and add it to the spanning tree. If
adding the edge created a cycle, then reject this edge.
Keep adding edges until we reach all vertices.
Example of Kruskal's algorithm
Page | 50
51 | P a g e
Page | 51