You are on page 1of 164

UNIT VI

TrEEs & Graphs


CONTENTS

➢ Basic Trees terminology,


➢ Binary trees and its representation,
➢ Insertion and deletion of nodes in binary tree,
➢ Binary search tree and its traversal,
➢ Heap,
➢ Balanced Binary Trees
➢ Threaded Binary tree,
➢ Graph Terminology and representation of graphs using adjacency
matrix,
★ Spanning tree
★ Graph Traversal - BFS & DFS

TREE DATA STRUCTURE
A tree is a nonlinear hierarchical data
structure that consists of nodes connected by
edges.
WHY TREE DATA STRUCTURE?
● Other data structures such as arrays, linked list, stack,
and queue are linear data structures that store data
sequentially.
● In order to perform any operation in a linear
data structure, the time complexity increases
with the increase in the data size.
● But, it is not acceptable in today's computational world.

● Different tree data structures allow quicker and


easier access to the data as it is a non-linear
data structure.
TREE TERMINOLOGIES
1. Node
● A node is an entity that contains a key or value and pointers
to its child nodes.
● The last nodes of each path are called leaf nodes or external
nodes that do not contain a link/pointer to child nodes.
● The node having at least a child node is called an internal
node.

2. Edge
It is the link between any two nodes.
3. Root
It is the topmost node of a tree.

4. Height of a Node
The height of a node is the number of edges from the node
to the deepest leaf (ie. the longest path from the node to a
leaf node).

5. Depth of a Node
The depth of a node is the number of edges from the root to
the node.

6. Height of a Tree
The height of a Tree is the height of the root node or the
depth of the deepest node.
7. Degree of a Node
The degree of a node is the total number of branches of
that node.

8. Forest
A collection of disjoint trees is called a forest.You
can create a forest by cutting the root of a tree.

Creating forest from a tree


● Root Node :- The root node is the topmost node in the tree
hierarchy. In other words, the root node is the one which doesn't
have any parent.
● Sub Tree :- If the root node is not null, the tree T1, T2 and T3
is called sub-trees of the root node.
● Leaf Node :- The node of tree, which doesn't have any child node,
is called leaf node. Leaf node is the bottom most node of the tree.
● Path :- The sequence of consecutive edges is called path. In the tree
shown in the above image, path to the node E is A→ B → E.
● Ancestor node:- An ancestor of a node is any predecessor node on a
path from root to that node. The root node doesn't have any ancestors. In
the tree shown in the above image, the node F have the ancestors, B
and A.
● Degree :- Degree of a node is equal to number of children, a node have. In
the tree shown in the above image, the degree of node B is 2. Degree of a
leaf node is always 0 while in a complete binary tree, degree of each node
is equal to 2.
● Level Number :- Each node of the tree is assigned a level number in such
a way that each node is present at one level higher than its parent. Root
node of the tree is always present at level 0.
TREE TRAVERSAL
In order to perform any operation on a tree, you need
to reach to the specific node. The tree traversal
algorithm helps in visiting a required node in the tree.
TREE TRAVERSAL - INORDER,PREORDER & POSTORDER
● Traversing a tree means visiting every node in the tree.
You might, for instance, want to add all the values in the
tree or find the largest one.
● For all these operations, you will need to visit each node
of the tree.
● Linear data structures like arrays, stacks, queues, and
linked list have only one way to read the data.
● But a hierarchical data structure like a tree can be
traversed in different ways.
Starting from top, Left to right

1 -> 12 -> 5 -> 6 -> 9

Starting from bottom, Left to right

5 -> 6 -> 12 -> 9 -> 1


Although this process is somewhat easy, it doesn't
respect the hierarchy of the tree, only the depth of the
nodes.

Instead, we use traversal methods that take into account


the basic structure of a tree i.e.

struct node {
int data;
struct node* left;
struct node*
right;
}
The struct node pointed to by left and right might have
other left and right children so we should think of them as
sub-trees instead of sub-nodes.
According to this structure, every tree is a combination of
➢ A node carrying data
➢ Two subtrees

Remember that our goal is to visit each node, so we


need to visit all the nodes in the subtree
INORDER TRAVERSAL

1) First, visit all the nodes in the left subtree


2) Then the root node
3) Visit all the nodes in the right subtree

inorder(root->left)
display(root->data)
inorder(root->right)
Preorder traversal

1) Visit root node


2) Visit all the nodes in the left subtree
3) Visit all the nodes in the right subtree

display(root->data)
preorder(root->left)
preorder(root->right)
POSTORDER TRAVERSAL

1) Visit all the nodes in the left subtree


2) Visit all the nodes in the right subtree
3) Visit the root node

postorder(root->left)
postorder(root->right)
display(root->data)
TYPES OF TREE
1. Binary Tree

2. Binary Search
Tree 3. AVL Tree
4. B-Tree
1. 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
There are different types of binary trees and they are…

1. Strictly Binary Tree


2. Complete Binary Tree
3. Extended Binary Tree
1. STRICTLY BINARY TREE
➢ 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
Example
2. COMPLETE BINARY TREE
➢ 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 and in complete binary tree all the nodes must have
exactly two children and at every level of complete binary tree
there must be 2level number of nodes.

➢ For example at level 2 there must be 2^2 = 4 nodes and at level 3


there must be 2^3 = 8 nodes.

➢ A binary tree in which every internal node has exactly two children
and all leaf nodes are at same level is called Complete Binary
Tree.

➢ Complete binary tree is also called as Perfect Binary Tree


3. EXTENDED BINARY TREE
➢ A binary tree can be converted 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.
➢ A normal binary tree is converted into full binary tree by
adding dummy nodes (In pink colour).
BINARY TREE REPRESENTATIONS
A binary tree data structure is represented using two
methods.
1. Array Representation

2. Linked List Representation

Consider the following binary


tree...
1. Array Representation of Binary Tree
In array representation of a binary tree, we use
one-dimensional array (1-D Array) to represent a binary
tree.
Consider the above example of a binary tree and it is
represented as follows…

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 a 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...
//Create Binary Tree

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

struct node
{
int data;
struct node *left;
struct node
*right;
};
/* newNode() allocates a new node with the given data and
NULL left and
right pointers. */
struct node* newNode(int data)
{
// Allocate memory for new node
struct node* node = (struct node*)malloc(sizeof(struct node));

// Assign data to this node


node->data = data;
// Initialize left and right children as NULL
node->left = NULL;
node->right = NULL;
return(node);
}
int main()
{
/*create root*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left =
newNode(4); getchar();
return 0;
}

//OUTPUT
123
BINARY SEARCH TREE(BST)
● Binary search tree is a data structure that quickly allows
us to maintain a sorted list of numbers.
● It is called a binary tree because each tree node has a
maximum of two children.
● 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

○ All nodes of left subtree are less than the root node
○ All nodes of right subtree are more than the root node
○ Both subtrees of each node are also BSTs i.e. they have
the above two properties
A tree having a right subtree with one value smaller than the root is shown to
demonstrate that it is not a valid binary search tree

The binary tree on the right isn't a binary search tree because the right subtree of the node
"3" contains a value smaller than it.
Binary Search Tree Operations-

Commonly performed operations on binary search tree


are-
1. Search Operation-
Search Operation is performed to search a
particular element in the Binary Search Tree.

Rules-
For searching a given key in the BST,

1) Compare the key with the value of root node.


2) If the key is present at the root node, then return the root
node.
3) If the key is greater than the root node value, then
recur for the root node’s right subtree.
4) If the key is smaller than the root node value, then
recur for the root node’s left subtree.
Example- Consider key = 45 has to be searched in the
given BST-

● We start our search from the root node 25.


● As 45 > 25, so we search in 25’s right subtree.
● As 45 < 50, so we search in 50’s left subtree.
● As 45 > 35, so we search in 35’s right subtree.
● As 45 > 44, so we search in 44’s right subtree but 44 has no subtrees.
● So, we conclude that 45 is not present in the above BST.
ALGORITHM: SEARCH

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)
2. Insertion Operation-
Insertion Operation is performed to insert an element
in the Binary Search Tree.
Rules-
1) The insertion of a new key always takes place as the
child of some leaf node.
2) For finding out the suitable leaf node,

Search the key to be inserted from the root node till


some leaf node is reached.
3) Once a leaf node is reached, insert the key as child

of that leaf node.


Example-
Consider the following example where key = 40
is inserted in the given BST-

● We start searching for value 40 from the root node 100.


● As 40 < 100, so we search in 100’s left subtree.
● As 40 > 20, so we search in 20’s right subtree.
● As 40 > 30, so we add 40 to 30’s right subtree.
ALGORITHM: INSERT

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;
3. Deletion Operation-

Deletion Operation is performed to delete a particular element from the


Binary Search Tree.

When it comes to deleting a node from the binary search tree, following
three cases are possible-

Case-01: Deletion Of A Node Having No Child (Leaf Node)-


Case-02: Deletion Of A Node Having Only One Child-
Case-03: Deletion Of A Node Having Two Children-
Case-01: Deletion Of A Node Having No Child (Leaf Node)-
Just remove / disconnect the leaf node that is to deleted from
the tree.
Example-
Consider the following example where node with value = 20
is deleted from the BST-
Case-02: Deletion Of A Node Having Only One Child-
Just make the child of the deleting node, the child of its
grandparent.
Example-
Consider the following example where node with value = 30
is deleted from the BST-
Case-02: Deletion Of A Node Having Two Children-
A node with two children may be deleted from the BST in
the following two ways-
Method-01:
Visit to the right subtree of the deleting node.
Pluck the least value element called as inorder
successor. Replace the deleting element with its inorder
successor.

Example-
Consider the following example where node with value = 15
is deleted from the BST-
Method-02:

● Visit to the left subtree of the deleting node.


● Pluck the greatest value element called as inorder predecessor.
● Replace the deleting element with its inorder predecessor.

Method-02:

● Visit to the left subtree of the deleting node.


● Pluck the greatest value element called as inorder predecessor.
● Replace the deleting element with its inorder predecessor.
Example-
Consider the following example where node with value = 15
is deleted from the BST-
Time Complexity-
Time complexity of all BST Operations =
O(h). Here, h = Height of binary search tree
Now, let us discuss the worst case and best
case. Worst Case-
➢ In worst case,
➢ The binary search tree is a skewed binary search tree.
➢ Height of the binary search tree becomes n. So,
Time complexity of BST Operations = O(n).
➢ In this case, binary search tree is as good as
unordered list with no benefits.
BINARY SEARCH TREE APPLICATIONS

1. In multilevel indexing in the database


2. For dynamic sorting
3. For managing virtual memory areas in Unix
kernel
Heap data structure

Heap data structure is a complete binary tree that


satisfies the heap property. It is also called as a binary
heap.
A complete binary tree is a special binary tree in which
every level, except possibly the last, is filled
all the nodes are as far left as possible
Heap Property is the property of a node in which

(for max heap) key of each node is always greater than


its child node/s and the key of the root node is the
largest among all other nodes;
(For min heap) key of each node is always smaller
than the child node/s and the key of the root node
is the smallest among all other nodes.
Heapify
Heapify is the process of creating a heap data
structure from a binary tree. It is used to create a Min-
Heap or a Max-Heap.

1. Let the input array be


2. Create a complete binary tree from the array
3. Start from the first index of non-leaf node whose
index is given by n/2 - 1.
4. Set current element i as largest.

5. The index of left child is given by 2i + 1 and the right

child is given by 2i + 2.

6. If leftChild is greater than currentElement (i.e.

element at ith index), set leftChildIndex as largest.

7. If rightChild is greater than element in largest, set

rightChildIndex as largest.

8. Swap largest with currentElement


Repeat steps 3-7 until the subtrees are also heapified.
EXAMPLE
To create a Max-Heap:

MaxHeap(array, size)
loop from the first index of non-leaf node down to zero call
heapify

For Min-Heap, both leftChild and rightChild must be smaller


than the parent for all nodes.
ALGORITHM FOR INSERTION IN MAX HEAP
If there is no node,
create a newNode.
else (a node is already present)
insert the newNode at the end (last node from left
to right.)

heapify the array


1. INSERT THE NEW ELEMENT AT THE END OF
THE TREE.
2. HEAPIFY THE TREE.

For Min Heap, the above algorithm is modified so that parentNode is always
smaller than newNode.
DELETE ELEMENT FROM HEAP
ALGORITHM FOR DELETION IN MAX HEAP
If nodeToBeDeleted is the leafNode
remove the node
Else swap nodeToBeDeleted with the lastLeafNode
remove noteToBeDeleted

heapify the array


1. SELECT THE ELEMENT TO BE DELETED.
2. SWAP IT WITH THE LAST ELEMENT.
3. REMOVE THE LAST ELEMENT.
HEAPIFY THE TREE.

For Min Heap, above algorithm is modified so that both


childNodes are greater smaller than currentNode.
PEEK (FIND MAX/MIN)

Peek operation returns the maximum element


from Max Heap or minimum element from Min
Heap without deleting the node.

For both Max heap and Min Heap

return rootNode
EXTRACT-MAX/MIN

Extract-Max returns the node with maximum


value after removing it from a Max Heap whereas
Extract-Min returns the node with minimum
after removing it from Min Heap.
BALANCED BINARY TREE
A balanced binary tree, also referred to as a height-balanced
binary tree, a binary tree is said to be balanced if the height
of left and right children of every node differ by either -1, 0
or
+1.
A binary tree is said to be balanced if, the difference
between the heights of left and right subtrees of
every node in the tree is either -1, 0 or +1.
Following are the conditions for a height-balanced binary
tree:
1. Difference between the left and the right subtree for any

node is not more than one


2. The left subtree is balanced

3. The right subtree is balanced


UNBALANCED BINARY TREE WITH DEPTH AT
EACH LEVEL
BALANCED BINARY TREE WITH DEPTH AT EACH
LEVEL
THREADED BINARY TREES
➢ A binary tree can be represented using array
representation or linked list representation.
➢ When a binary tree is represented using linked list
representation, the reference part of the node which
doesn't have a child is filled with a NULL pointer.
➢ In any binary tree linked list representation, there is a
number of NULL pointers than actual pointers.
➢ Generally, in any binary tree linked list representation, if
there are 2N number of reference fields, then N+1 number
of reference fields are filled with NULL ( N+1 are NULL
out of 2N ).
➢ This NULL pointer does not play any role except indicating
that there is no link (no child).
THREADED BINARY TREES….
➢ "Threaded Binary Tree", which makes use of NULL
pointers to improve its traversal process.
➢ In a threaded binary tree, NULL pointers are replaced
by references of other nodes in the tree. These extra
references are called as threads.
➢ Threaded Binary Tree is also a binary tree in which all left
child pointers that are NULL (in Linked list
representation) points to its in-order predecessor, and all
right child pointers that are NULL (in Linked list
representation) points to its in-order successor.
To convert the above example binary tree into a threaded binary tree,
first find the in-order traversal of that tree…

In-order traversal of above binary


tree... H - D - I - B - E - A - F - J - C - G
● But here the node G does not have its in-order
successor, so it points to the root node A.
● Threads are indicated with dotted links.
AVL TREE DATA STRUCTURE
➢ AVL tree is a height-balanced binary search tree. That
means, an AVL tree is also a binary search tree but
it is a balanced tree.
➢ A binary tree is said to be balanced if, the difference
between the heights of left and right subtrees of every
node in the tree is either -1, 0 or +1.
➢ In other words, a binary tree is said to be balanced if the
height of left and right children of every node differ by
either -1, 0 or +1.
➢ In an AVL tree, every node maintains an extra
information known as balance factor. The AVL tree was
introduced in the year 1962 by G.M. Adelson-Velsky
and E.M. Landis.
AVL TREE DATA STRUCTURE
➢ Balance factor of a node is the difference between the
heights of the left and right subtrees of that node.
➢ The balance factor of a node is calculated either height of
left subtree - height of right subtree (OR) height of right
subtree - height of left subtree.

Balance factor = heightOfLeftSubtree - heightOfRightSubtree


EXAMPLE OF AVL TREE

➢ The above tree is a binary search tree and every node is satisfying
balance factor condition. So this tree is said to be an AVL tree.
➢ Every AVL Tree is a binary search tree but every Binary Search
Tree need not be AVL tree.
AVL Tree Rotations

➢ In AVL tree, after performing operations like insertion


and deletion we need to check the balance factor of
every node in the tree.
➢ If every node satisfies the balance factor condition
then we conclude the operation otherwise we must
make it balanced.
➢ Whenever the tree becomes imbalanced due to any
operation we use rotation operations to make the
tree balanced.

❖ Rotation operations are used to make the tree


balanced.
❖ Rotation is the process of moving nodes either to left
or to right to make the tree balanced.
There are four rotations and they are classified into two
types.
Single Left Rotation (LL Rotation)

In LL Rotation, every node moves one position to left from the current
position.
Single Right Rotation (RR Rotation)

In RR Rotation, every node moves one position to right from the current
position.
Left Right Rotation (LR Rotation)

The LR Rotation is a sequence of single left rotation followed by a single


right rotation. In LR Rotation, at first, every node moves one position to
the left and one position to right from the current position.
Right Left Rotation (RL Rotation)

The RL Rotation is sequence of single right rotation followed by single left


rotation. In RL Rotation, at first every node moves one position to right and
one position to left from the current position.
Operations on an AVL Tree

The following operations are performed on AVL tree...

1. Search

2. Insertion

3. Deletion
SEARCH OPERATION IN AVL TREE
In an AVL tree, the search operation is performed with O(log n) time complexity. The search
operation in the AVL tree is similar to the search operation in a Binary search tree.
Step 1 - Read the search element from the user.
Step 2 - Compare the search element with the value of root node in the tree.
Step 3 - If both are matched, then display "Given node is found!!!" and terminate the function
Step 4 - If both are not matched, then check whether search element is smaller or larger than
that node value.
Step 5 - If search element is smaller, then continue the search process in left
subtree.
Step 6 - If search element is larger, then continue the search process in right
subtree.
Step 7 - Repeat the same until we find the exact element or until the search element is
compared with the leaf node.
Step 8 - If we reach to the node having the value equal to the search value, then display
"Element is found" and terminate the function.
Step 9 - If we reach to the leaf node and if it is also not matched with the search element, then
display "Element is not found" and terminate the function.
INSERTION OPERATION IN AVL TREE

In an AVL tree, the insertion operation is performed with O(log n) time complexity. In
AVL Tree, a new node is always inserted as a leaf node. The insertion operation is
performed as follows...

Step 1 - Insert the new element into the tree using Binary Search Tree insertion logic.
Step 2 - After insertion, check the Balance Factor of every node.
Step 3 - If the Balance Factor of every node is 0 or 1 or -1 then go for next
operation.
Step 4 - If the Balance Factor of any node is other than 0 or 1 or -1 then that tree is said
to be imbalanced. In this case, perform suitable Rotation to make it balanced and go
for next operation.
EXAMPLE: CONSTRUCT AN AVL TREE BY
INSERTING NUMBERS FROM 1 TO 8.
DELETION OPERATION IN AVL TREE

➢ The deletion operation in AVL Tree is similar to


deletion operation in BST.
➢ But after every deletion operation, we need to check
with the Balance Factor condition.
➢ If the tree is balanced after deletion go for next
operation otherwise perform suitable rotation to
make the tree Balanced.
GRAPH
GRAPH DATA STRUCTURE
➢ A graph data structure is a collection of nodes that
have data and are connected to other nodes.
➢ 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.
Graph Definition

➢ All of facebook is then a collection of these nodes


and edges. This is because facebook uses a graph
data structure to store its data.
➢ More precisely, a graph is a data structure (V, E) that
consists of
A collection of vertices V
A collection of edges E, represented as ordered
pairs of vertices (u,v) OR
➢ Set of vertices (nodes) and edges connecting
them G = ( V, E )
where
V is a set of vertices: V = { vi }
An edge connects two vertices: e = ( vi , vj )
E is a set of edges: E = { (vi , vj ) }
Vertices and edges

In the graph,

V = {0, 1, 2, 3}
E = {(0,1), (0,2), (0,3), (1,2)}
G = {V, E}
GRAPH TERMINOLOGY

● Adjacency: A vertex is said to be adjacent to another vertex if there is


an edge connecting them. Vertices 2 and 3 are not adjacent
because there is no edge between them.
● Path: A sequence of edges that allows you to go from vertex A to
vertex B is called a path. 0-1, 1-2 and 0-2 are paths from vertex 0
to vertex 2.
● Directed Graph: A graph in which an edge (u,v) doesn't necessarily
mean that there is an edge (v, u) as well. The edges in such a graph
are represented by arrows to show the direction of the edge.
GRAPH REPRESENTATION

Graphs are commonly represented in two ways:

1. Adjacency Matrix
2. Adjacency List
1. ADJACENCY MATRIX
➢ An adjacency matrix is a 2D array of V x V vertices.
➢ Each row and column represent a vertex.
➢ If the value of any element a[i][j] is 1, it represents that
there is an edge connecting vertex i and vertex j.
➢ The adjacency matrix for the graph we created above is
➢ Since it is an undirected graph, for edge (0,2), we also
need to mark edge (2,0); making the adjacency matrix
symmetric about the diagonal.
➢ Edge lookup(checking if an edge exists between vertex
A and vertex B) is extremely fast in adjacency matrix
representation but we have to reserve space for every
possible link between all vertices(V x V), so it requires
more space.
2. ADJACENCY LIST REPRESENTATION
➢ An adjacency list represents a graph as an array of linked lists.
➢ The index of the array represents a vertex and each element in
its linked list represents the other vertices that form an edge
with the vertex.
➢ The adjacency list for the graph we made in the first example is
as follows:
➢ An adjacency list is efficient in terms of storage because we only
need to store the values for the edges. For a graph with millions
of vertices, this can mean a lot of saved space.
GRAPH OPERATIONS

The most common graph operations are:


➢ Check if the element is present in the graph
➢ Graph Traversal
➢ Add elements(vertex, edges) to graph
➢ Finding the path from one vertex to another
SPANNING TREE AND MINIMUM SPANNING
TREE
➢ Before we learn about spanning trees, we need to
understand two graphs: undirected graphs and connected
graphs.
➢ An undirected graph is a graph in which the edges do not
point in any direction (ie. the edges are bidirectional).
CONNECTED GRAPH

A connected graph is a graph in which there is


always a path from a vertex to any other vertex.
SPANNING TREE
➢ A spanning tree is a sub-graph of an undirected connected
graph, which includes all the vertices of the graph with 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).
➢ If we have n = 4, the maximum number of possible
spanning trees is equal to 4^(4-2) = 16.
➢ Thus, 16 spanning trees can be formed from a complete
graph with 4 vertices.
EXAMPLE OF A SPANNING TREE
Let the original graph be:

Normal graph
Some of the possible spanning trees that can be
created from the above graph are:
MINIMUM SPANNING TREE
➢ A minimum spanning tree is a spanning tree in
which the sum of the weight of the edges is as
minimum as possible.
➢ Example of a Spanning Tree
➢ Let's understand the above definition with the help of
the example below.
➢ The initial graph is:

Weighted graph
THE POSSIBLE SPANNING TREES FROM THE ABOVE
GRAPH ARE:
THE MINIMUM SPANNING TREE FROM THE
ABOVE SPANNING TREES IS:
GRAPH TRAVERSAL - BFS & DFS
➢ Graph traversal is a technique used for searching
a vertex in a graph.
➢ The graph traversal is also used to decide the order of
vertices is visited in the search process.
➢ A graph traversal finds the edges to be used in
the search process without creating loops.
➢ That means using graph traversal we visit all the
vertices of the graph without getting into looping
path.
There are two graph traversal techniques and they are as
follows...

DFS (Depth First Search)


BFS (Breadth First Search)
BFS (BREADTH FIRST SEARCH)
➢ BFS traversal of a graph produces a spanning tree as final
result. Spanning Tree is a graph without loops.
➢ We use Queue data structure with maximum size of total
number of vertices in the graph to implement BFS
traversal.
We use the following steps to implement BFS traversal...
Step 1 - Define a Queue of size total number of vertices in the
graph.
Step 2 - Select any vertex as starting point for traversal. Visit that
vertex and insert it into the Queue.
Step 3 - Visit all the non-visited adjacent vertices of the vertex
which is at front of the Queue and insert them into the Queue.
Step 4 - When there is no new vertex to be visited from the vertex
which is at front of the Queue then delete that vertex.
Step 5 - Repeat steps 3 and 4 until queue becomes empty.
Step 6 - When queue becomes empty, then produce final spanning
tree by removing unused edges from the graph
DFS (Depth First Search)
DFS traversal of a graph produces a spanning tree as final result.
Spanning Tree is a graph without loops. We use Stack data structure
with maximum size of total number of vertices in the graph to
implement DFS traversal.
We use the following steps to implement DFS traversal...
Step 1 - Define a Stack of size total number of vertices in the graph.
Step 2 - Select any vertex as starting point for traversal. Visit that
vertex and push it onto the Stack.
Step 3 - Visit any one of the non-visited adjacent vertices of a vertex
which is at the top of stack and push it onto the stack.
Step 4 - Repeat step 3 until there is no new vertex to be visited from
the vertex which is at the top of the stack.
Step 5 - When there is no new vertex to visit then use backtracking and
pop one vertex from the stack.
Step 6 - Repeat steps 3, 4 and 5 until stack becomes Empty.
Step 7 - When stack becomes Empty, then produce final spanning tree
by removing unused edges from the graph
Backtracking is coming back to the vertex from which we reached the
current vertex.
Floyd-Warshall Algorithm
➢ Floyd-Warshall Algorithm is an algorithm for finding the
shortest path between all the pairs of vertices in a weighted
graph.
➢ This algorithm works for both the directed and undirected
weighted graphs.
➢ But, it does not work for the graphs with negative cycles
(where the sum of the edges in a cycle is negative).
➢ A weighted graph is a graph in which each edge has a
numerical value associated with it.
➢ Floyd-Warshall algorithm is also called as Floyd's
algorithm, Roy-Floyd algorithm, Roy-Warshall
algorithm, or WFI algorithm.
➢ This algorithm follows the dynamic programming
approach to find the shortest paths.
HOW FLOYD-WARSHALL ALGORITHM WORKS?
1. Create a matrix A0 of dimension n*n where n is the number
of vertices. The row and the column are indexed as i
and j respectively. i and j are the vertices of the graph.
➢ Each cell A[i][j] is filled with the distance from the ith vertex
to the jth vertex. If there is no path from ith vertex to jth
vertex, the cell is left as infinity.

Fill each cell with the distance between ith and jth vertex
2. Now, create a matrix A1 using matrix A0. The elements in
the first column and the first row are left as they are. The
remaining cells are filled in the following way.

Let k be the intermediate vertex in the shortest path from


source to destination. In this step, k is the first vertex. A[i][j]
is filled with (A[i][k] + A[k][j]) if (A[i][j] > A[i][k] + A[k][j]).

That is, if the direct distance from the source to the


destination is greater than the path through the vertex k,
then the cell is filled with A[i][k] + A[k][j].

In this step, k is vertex 1. We calculate the distance from


source vertex to destination vertex through this vertex k.
Calculate the distance from the source vertex to destination vertex through this
vertex k

For example: For A1[2, 4], the direct distance from vertex 2 to 4 is 4 and
the sum of the distance from vertex 2 to 4 through vertex (ie. from vertex 2
to 1 and from vertex 1 to 4) is 7. Since 4 < 7, A0[2, 4] is filled with 4.
3. Similarly, A2 is created using A3. The elements in the
second column and the second row are left as they are.

In this step, k is the second vertex (i.e. vertex 2).


The remaining steps are the same as in step 2.

Calculate the distance from the source vertex to destination vertex through this vertex 2
4. Similarly, A^3 and A^4 is also created.

Calculate the distance from the source vertex to destination vertex through this
vertex 3
Calculate the distance from the source vertex to destination vertex through
this vertex 4

5. A^4 gives the shortest path between each pair of vertices.


FLOYD-WARSHALL ALGORITHM
n = no of vertices
A = matrix of dimension n*n
for k = 1 to n
for i = 1 to n
for j = 1 to n
Ak[i, j] = min (Ak-1[i, j], Ak-1[i, k] + Ak-1[k, j])
return A
FLOYD WARSHALL ALGORITHM COMPLEXITY

Time Complexity
There are three loops. Each loop has
constant complexities. So, the time
complexity of the Floyd-Warshall algorithm
is O(n^3).

Space Complexity
The space complexity of the Floyd-Warshall algorithm
is O(n^2).
FLOYD WARSHALL ALGORITHM APPLICATIONS

➢ To find the shortest path is a directed graph


➢ To find the transitive closure of directed graphs
➢ To find the Inversion of real matrices
➢ For testing whether an undirected graph is bipartite
Thank You

You might also like