0% found this document useful (0 votes)
44 views

Trees and Graphs ppt

Uploaded by

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

Trees and Graphs ppt

Uploaded by

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

Module 4: Trees and Graphs

Trees
• Basic Terminology,
• Binary Trees and their Representation,
• Complete Binary Trees, Binary Search Trees,
• Operations on Binary Trees (Insertion, Deletion, Search &
Traversal),
• Application: Expression Evaluation.
Graphs
• Terminology and Representations,
• Graphs & Multigraphs,
• Directed Graphs,
• Sequential Representation of Graphs,
• Adjacency Matrices, Graph Transversal,
• Connected Components and Spanning Trees.
Trees
• We read the linear data structures like an array, linked list, stack and queue in
which all the elements are arranged in a sequential manner. The different data
structures are used for different kinds of data.
• Some factors are considered for choosing the data structure:
• What type of data needs to be stored?: It might be a possibility that a certain
data structure can be the best fit for some kind of data.
• Cost of operations: If we want to minimize the cost for the operations for the
most frequently performed operations. For example, we have a simple list on
which we have to perform the search operation; then, we can create an array in
which elements are stored in sorted order to perform the binary search. The
binary search works very fast for the simple list as it divides the search space into
half.
• Memory usage: Sometimes, we want a data structure that utilizes less memory.
• A tree is also one of the data structures that represent hierarchical
data. Suppose we want to show the employees and their positions in
the hierarchical form then it can be represented as shown below:

• The above tree shows the organization hierarchy of some company.
In the above structure, john is the CEO of the company, and John has
two direct reports named as Steve and Rohan. Steve has three direct
reports named Lee, Bob, Ella where Steve is a manager. Bob has two
direct reports named Sal and Emma. Emma has two direct reports
named Tom and Raj. Tom has one direct report named Bill. This
particular logical structure is known as a Tree. Its structure is similar
to the real tree, so it is named a Tree. In this structure, the root is at
the top, and its branches are moving in a downward direction.
Therefore, we can say that the Tree data structure is an efficient way
of storing the data in a hierarchical way.
• Let's understand some key points of the Tree data structure.
• A tree data structure is defined as a collection of objects or entities known
as nodes that are linked together to represent or simulate hierarchy.
• A tree data structure is a non-linear data structure because it does not
store in a sequential manner. It is a hierarchical structure as elements in a
Tree are arranged in multiple levels.
• In the Tree data structure, the topmost node is known as a root node. Each
node contains some data, and data can be of any type. In the above tree
structure, the node contains the name of the employee, so the type of data
would be a string.
• Each node contains some data and the link or reference of other nodes
that can be called children.
Basic Terminology
Basic Terminology In Tree Data Structure:
• Parent Node: The node which is a predecessor of a node is called the
parent node of that node. {2} is the parent node of {6, 7}.
• Child Node: The node which is the immediate successor of a node is called
the child node of that node. Examples: {6, 7} are the child nodes of {2}.
• Root Node: The topmost node of a tree or the node which does not have
any parent node is called the root node. {1} is the root node of the tree. A
non-empty tree must contain exactly one root node.
• Degree of a Node: The total count of subtrees attached to that node is
called the degree of the node. The degree of a leaf node must be 0. The
degree of a tree is the degree of its root. The degree of the node {3} is 3.
• Leaf Node or External Node: The nodes which do not have any child nodes
are called leaf nodes. {6, 14, 8, 9, 15, 16, 4, 11, 12, 17, 18, 19} are the leaf
nodes of the tree.
• Ancestor of a Node: Any predecessor nodes on the path of the root to that
node are called Ancestors of that node. {1, 2} are the parent nodes of the
node {7}
• Descendant: Any successor node on the path from the leaf node to that
node. {7, 14} are the descendants of the node. {2}.
• Sibling: Children of the same parent node are called siblings. {8, 9, 10} are
called siblings.
• Depth of a node: The count of edges from the root to the node. Depth of
node {14} is 3.
• Height of a node: The number of edges on the longest path from that
node to a leaf. Height of node {3} is 2.
• Height of a tree: The height of a tree is the height of the root node i.e
the count of edges from the root to the deepest node. The height of
the above tree is 3.
• Level of a node: The count of edges on the path from the root node
to that node. The root node has level 0.
• Internal node: A node with at least one child is called Internal Node.
• Subtree: Any node of the tree along with its descendants
Implementation of Tree

• The tree data structure can be created by creating the nodes


dynamically with the help of the pointers. The tree in the memory can
be represented as shown below:
• The above figure shows the representation of the tree data structure in the
memory. In the above structure, the node contains three fields. The second
field stores the data; the first field stores the address of the left child, and
the third field stores the address of the right child.
• In programming, the structure of a node can be defined as:
struct node
{
int data;
struct node *left;
struct node *right;
};
Applications of trees

• Storing naturally hierarchical data: Trees are used to store the data in
the hierarchical structure. For example, the file system. The file
system stored on the disc drive, the file and folder are in the form of
the naturally hierarchical data and stored in the form of trees.
• Organize data: It is used to organize data for efficient insertion,
deletion and searching.
• Routing table: The tree data structure is also used to store the data in
routing tables in the routers.
Types of Tree data structure

• General tree: The general tree is one of the types of tree data structure. In the general tree, a
node can have either 0 or maximum n number of nodes. There is no restriction imposed on the
degree of the node (the number of nodes that a node can contain). The topmost node in a
general tree is known as a root node. The children of the parent node are known as subtrees.
• There can be n number of subtrees in a general tree. In the general
tree, the subtrees are unordered as the nodes in the subtree cannot
be ordered.
Every non-empty tree has a downward edge, and these edges are
connected to the nodes known as child nodes. The root node is
labeled with level 0. The nodes that have the same parent are known
as siblings.
• Binary tree: Here, binary name itself suggests two numbers, i.e., 0
and 1. In a binary tree, each node in a tree can have utmost two child
nodes. Here, utmost means whether the node has 0 nodes, 1 node
or 2 nodes.
• Binary Search tree: Binary search tree is a non-linear data structure in
which one node is connected to n number of nodes. It is a node-
based data structure. A node can be represented in a binary search
tree with three fields, i.e., data part, left-child, and right-child. A node
can be connected to the utmost two child nodes in a binary search
tree, so the node contains two pointers (left child and right child
pointer).
Every node in the left subtree must contain a value less than the value
of the root node, and the value of each node in the right subtree
must be bigger than the value of the root node.
• A node can be created with the help of a user-defined data type known
as struct, as shown below:
struct node
{
int data;
struct node *left;
struct node *right;
}
The above is the node structure with three fields: data field, the second field
is the left pointer of the node type, and the third field is the right pointer of
the node type.
Binary Tree

• The Binary tree means that the node can have maximum two
children. Here, binary name itself suggests that 'two'; therefore, each
node can have either 0, 1 or 2 children.
• The above tree is a binary tree because each node contains the
utmost two children. The logical representation of the above tree is
given below:

• In the above tree, node 1 contains two pointers, i.e., left and a right
pointer pointing to the left and right node respectively. The node 2
contains both the nodes (left and right node); therefore, it has two
pointers (left and right). The nodes 3, 5 and 6 are the leaf nodes, so
all these nodes contain NULL pointer on both left and right parts.
Properties of Binary Tree

• At each level of i, the maximum number of nodes is 2i.


• The height of the tree is defined as the longest path from the root
node to the leaf node. The tree which is shown above has a height
equal to 3. Therefore, the maximum number of nodes at height 3 is
equal to (1+2+4+8) = 15. In general, the maximum number of nodes
possible at height h is (20 + 21 + 22+….2h) = 2h+1 -1.
• The minimum number of nodes possible at height h is equal to h+1.
• If the number of nodes is minimum, then the height of the tree would
be maximum. Conversely, if the number of nodes is maximum, then
the height of the tree would be minimum.
• f there are 'n' number of nodes in the binary tree.
• The minimum height can be computed as:
• As we know that,
• n = 2h+1 -1
• n+1 = 2h+1
• Taking log on both the sides,
• log2(n+1) = log2(2h+1)
• log2(n+1) = h+1
• h = log2(n+1) - 1
• The maximum height can be computed as:
• As we know that,
• n = h+1
• h= n-1
Types of Binary Tree

• Full/ proper/ strict Binary tree


• Complete Binary tree
• Perfect Binary tree
• 1. Full/ proper/ strict Binary tree
• The full binary tree is also known as a strict binary tree. The tree can
only be considered as the full binary tree if each node must contain
either 0 or 2 children. The full binary tree can also be defined as the
tree in which each node must contain 2 children except the leaf
nodes.
In the above tree, we can observe that each node is either
containing zero or two children; therefore, it is a Full Binary
tree.
Properties of Full Binary Tree
• The maximum number of nodes is the same as the number of nodes
in the binary tree, i.e., 2h+1 -1.
• The minimum number of nodes in the full binary tree is 2*h+1.
• The minimum height of the full binary tree is log2(n+1) - 1.
• The maximum height of the full binary tree can be computed as:
• n= 2*h + 1
• n-1 = 2*h
• h = n-1/2
Complete Binary Tree
• The complete binary tree is a tree in which all the nodes are
completely filled except the last level. In the last level, all the nodes
must be as left as possible. In a complete binary tree, the nodes
should be added from the left.
The above tree is a complete binary tree because all the nodes
are completely filled, and all the nodes in the last level are
added at the left first.
Properties of Complete Binary Tree
• The maximum number of nodes in complete binary tree is 2h+1 - 1.
• The minimum number of nodes in complete binary tree is 2h.
• The minimum height of a complete binary tree is log2(n+1) - 1.
• The maximum height of a complete binary tree is log2n
Perfect Binary Tree
• A tree is a perfect binary tree if all the internal nodes have 2 children,
and all the leaf nodes are at the same level.
Binary Tree Implementation

• A Binary tree is implemented with the help of pointers. The first node in
the tree is represented by the root pointer. Each node in the tree consists
of three parts, i.e., data, left pointer and right pointer. To create a binary
tree, we first need to create the node. We will create the node of user-
defined as shown below:
struct node
{
int data,
struct node *left, *right;
}
In the above structure, data is the value, left pointer contains the address of
the left node, and right pointer contains the address of the right node.
Binary Tree program in C
#include<stdio.h>
struct node
{
int data;
struct node *left, *right;
};
void main()
{
struct node *root;
root = create();
}
struct node *create()
{
struct node *temp;
int data;
temp = (struct node *)malloc(sizeof(struct node));
printf("Press 0 to exit");
printf("\nPress 1 for new node");
printf("Enter your choice : ");
scanf("%d", &choice);
if(choice==0)
{
return 0;
}
else
{
printf("Enter the data:");
scanf("%d", &data);
temp->data = data;
printf("Enter the left child of %d", data);
temp->left = create();
printf("Enter the right child of %d", data);
temp->right = create();
return temp;
}
}
• The above code is calling the create() function recursively and
creating new node on each recursive call. When all the nodes are
created, then it forms a binary tree structure. The process of visiting
the nodes is known as tree traversal. There are three types traversals
used to visit a node:
• Inorder traversal
• Preorder traversal
• Postorder traversal
Binary Search Tree

1.Binary Search tree can be defined as a class of binary trees, in which


the nodes are arranged in a specific order. This is also called ordered
binary tree.
2.In a binary search tree, the value of all the nodes in the left sub-tree
is less than the value of the root.
3.Similarly, value of all the nodes in the right sub-tree is greater than or
equal to the value of the root.
4.This rule will be recursively applied to all the left and right sub-trees
of the root.
• A Binary search tree is shown in the above figure. As the constraint
applied on the BST, we can see that the root node 30 doesn't contain
any value greater than or equal to 30 in its left sub-tree and it also
doesn't contain any value less than 30 in its right sub-tree.
Advantages of using binary search tree

1.Searching become very efficient in a binary search tree since, we get


a hint at each step, about which sub-tree contains the desired
element.
2.The binary search tree is considered as efficient data structure in
compare to arrays and linked lists. In searching process, it removes
half sub-tree at every step.
3.It also speed up the insertion and deletion operations as compare to
that in array and linked list.
Create the binary search tree using the following
data elements.
• 43, 10, 79, 90, 12, 54, 11, 9, 50
1.Insert 43 into the tree as the root of the tree.
2.Read the next element, if it is lesser than the root node element,
insert it as the root of the left sub-tree.
3.Otherwise, insert it as the root of the right of the right sub-tree.
• The process of creating BST by using the given elements, is shown in
the image below.
Operations on Binary Search Tree

SN Operation Description
1 Searching in BST Finding the location of some specific element in a
binary search tree.

2 Insertion in BST Adding a new element to the binary search tree at


the appropriate location so that the property of
BST do not violate.

3 Deletion in BST Deleting some specific node from a binary search


tree. However, there can be various cases in
deletion depending upon the number of children,
the node have.
Searching

• Searching means finding or locating some specific element or node within


a data structure. However, searching for some specific node in binary
search tree is pretty easy due to the fact that, element in BST are stored in
a particular order.
1.Compare the element with the root of the tree.
2.If the item is matched then return the location of the node.
3.Otherwise check if item is less than the element present on root, if so then
move to the left sub-tree.
4.If not, then move to the right sub-tree.
5.Repeat this procedure recursively until match found.
6.If element is not found then return NULL.
Insertion

• Insert function is used to add a new element in a binary search tree at


appropriate location. Insert function is to be designed in such a way that, it
must not violate the property of binary search tree at each value.
1.Allocate the memory for tree.
2.Set the data part to the value and set the left and right pointer of tree,
point to NULL.
3.If the item to be inserted, will be the first element of the tree, then the left
and right of this node will point to NULL.
4.Else, check if the item is less than the root element of the tree, if this is
true, then recursively perform this operation with the left of the root.
5.If this is false, then perform this operation recursively with the right sub-
tree of the root.
C Function

#include<stdio.h>
#include<stdlib.h>
void insert(int);
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *root;
void main ()
{
int choice,item;
do
{
printf("\nEnter the item which you want to insert?\n");
scanf("%d",&item);
insert(item);
printf("\nPress 0 to insert more ?\n");
scanf("%d",&choice);
}while(choice == 0);
}
void insert(int item)
{
struct node *ptr, *parentptr , *nodeptr;
ptr = (struct node *) malloc(sizeof (struct node));
if(ptr == NULL)
{
printf("can't insert");
}
else
{
ptr -> data = item;
ptr -> left = NULL;
ptr -> right = NULL;
if(root == NULL)
{
root = ptr;
root -> left = NULL;
root -> right = NULL;
}
else
{
parentptr = NULL;
nodeptr = root;
while(nodeptr != NULL)
{
parentptr = nodeptr;
if(item < nodeptr->data)
{
nodeptr = nodeptr -> left;
}
else
{
nodeptr = nodeptr -> right;
}
}
if(item < parentptr -> data)
{
parentptr -> left = ptr;
}
else
{
parentptr -> right = ptr;
}
}
printf("Node Inserted");
}
}
Deletion

• Delete function is used to delete the specified node from a binary


search tree. However, we must delete a node from a binary search
tree in such a way, that the property of binary search tree doesn't
violate. There are three situations of deleting a node from binary
search tree.
The node to be deleted is a leaf node

• It is the simplest case, in this case, replace the leaf node with the
NULL and simple free the allocated space.
• In the following image, we are deleting the node 85, since the node is
a leaf node, therefore the node will be replaced with NULL and
allocated space will be freed.
The node to be deleted has only one child.

• In this case, replace the node with its child and delete the child node,
which now contains the value which is to be deleted. Simply replace it
with the NULL and free the allocated space.
• In the following image, the node 12 is to be deleted. It has only one
child. The node will be replaced with its child node and the replaced
node 12 (which is now leaf node) will simply be deleted.
The node to be deleted has two children.

• It is a bit complexed case compare to other two cases. However, the


node which is to be deleted, is replaced with its in-order successor or
predecessor recursively until the node value (to be deleted) is placed
on the leaf of the tree. After the procedure, replace the node with
NULL and free the allocated space.
• In the following image, the node 50 is to be deleted which is the root
node of the tree. The in-order traversal of the tree given below.
• 6, 25, 30, 50, 52, 60, 70, 75.
• replace 50 with its in-order successor 52. Now, 50 will be moved to
the leaf of the tree, which will simply be deleted.
C Function for Deletion
struct Node {
int data;
struct Node *left;
struct Node *right;
};
//Function to find minimum in a tree.
Struct Node* FindMin(struct Node* root)
{
while(root->left != NULL) root = root->left;
return root;
}
// Function to search a delete a value from tree.
struct Node* Delete(struct Node *root, int data) {
if(root == NULL) return root;
else if(data < root->data) root->left = Delete(root->left,data);
else if (data > root->data) root->right = Delete(root->right,data);
// Wohoo... I found you, Get ready to be deleted
else {
// Case 1: No child
if(root->left == NULL && root->right == NULL) {
free(root);
root = NULL;
}
//Case 2: One child
else if(root->left == NULL) {
struct Node *temp = root;
root = root->right;
free(temp);
}
else if(root->right == NULL) {
struct Node *temp = root;
root = root->left;
free(temp);
}
// case 3: 2 children
else {
struct Node *temp = FindMin(root->right);
root->data = temp->data;
root->right = Delete(root->right,temp->data);
}
}
return root;
}
Tree Traversal

• Here, tree traversal means traversing or visiting each node of a tree.


Linear data structures like Stack, Queue, linked list have only one way
for traversing, whereas the tree has various ways to traverse or visit
each node. The following are the three different ways of traversal:
• Inorder traversal
• Preorder traversal
• Postorder traversal
Inorder Traversal

• An inorder traversal is a traversal technique that follows the policy,


i.e., Left Root Right. Here, Left Root Right means that the left subtree
of the root node is traversed first, then the root node, and then the
right subtree of the root node is traversed. Here, inorder name itself
suggests that the root node comes in between the left and the right
subtrees.
• Consider the below tree for the inorder traversal.
• First, we will visit the left part, then root, and then the right part of
performing the inorder traversal. In the above tree, A is a root node, so we
move to the left of the A, i.e., B. As node B does not have any left child so B
will be printed as shown below:

• After visiting node B, we move to the right child of node B, i.e., D. Since
node D is a leaf node, so node D gets printed as shown below:
• The left part of node A is traversed. Now, we will visit the root node,
i.e., A, and it gets printed as shown below:

• Once the traversing of left part and root node is completed, we move
to the right part of the root node. We move to the right child of node
A, i.e., C. The node C has also left child, i.e., E and E has also left child,
i.e., G. Since G is a leaf node, so G gets printed as shown below:
The root node of G is E, so it gets printed as shown below

Since E does not have any right child, so we move to the root of
the E node, i.e., C. C gets printed as shown below:
Once the left part of node C and the root node, i.e., C, are
traversed, we move to the right part of Node C. We move to
the node F and node F has a left child, i.e., H. Since H is a leaf
node, so it gets printed as shown below:
• Now we move to the root node of H, i.e., F and it gets printed as
shown below:

• After visiting the F node, we move to the right child of node F, i.e., I,
and it gets printed as shown below:

Therefore, the inorder traversal of the above tree is B, D, A, G,


E, C, H, F, I.
Preorder Traversal

• A preorder traversal is a traversal technique that follows the policy,


i.e., Root Left Right. Here, Root Left Right means root node of the
tree is traversed first, then the left subtree and finally the right
subtree is traversed. Here, the Preorder name itself suggests that the
root node would be traversed first.
• Consider the below tree for the Preorder traversal.
• To perform the preorder traversal, we first visit the root node, then
the left part, and then we traverse the right part of the root node. As
node A is the root node in the above tree, so it gets printed as shown
below:
• Once the root node is traversed, we move to the left subtree. In the
left subtree, B is the root node for its right child, i.e., D. Therefore, B
gets printed as shown below:

• Since node B does not have a left child, and it has only a right child;
therefore, D gets printed as shown below:
• Once the left part of the root node A is traversed, we move to the
right part of node A. The right child of node A is C. Since C is a root
node for all the other nodes; therefore, C gets printed as shown
below:

Now we move to the left child, i.e., E of node C. Since node E is


a root node for node G; therefore, E gets printed as shown
below:
The node E has a left child, i.e., G, and it gets printed as shown
below:

Since the left part of the node C is completed, so we move to


the right part of the node C. The right child of node C is node F.
The node F is a root node for the nodes H and I; therefore, the
node F gets printed as shown below:
Once the node F is visited, we will traverse the left child, i.e., H
of node F as shown below:

Now we will traverse the right child, i.e., I of node F, as shown


below:
Therefore, the preorder traversal of the above tree is A, B, D, C,
E, G, F, H, I.
Postorder Traversal

• A Postorder traversal is a traversal technique that follows the policy,


i.e., Left Right Root. Here, Left Right Root means the left subtree of
the root node is traversed first, then the right subtree, and finally, the
root node is traversed. Here, the Postorder name itself suggests that
the root node of the tree would be traversed at the last.
• Consider the below tree for the Postorder traversal.

• To perform the postorder traversal, we first visit the left part, then the
right part, and then we traverse the root node. In the above tree, we
move to the left child, i.e., B of node A. Since B is a root node for the
node D; therefore, the right child, i.e., D of node B, would be
traversed first and then B as shown below:
• Once the traversing of the left subtree of node A is completed, then
the right part of node A would be traversed. We move to the right
child of node A, i.e., C. Since node C is a root node for the other
nodes, so we move to the left child of node C, i.e., node E. The node E
is a root node, and node G is a left child of node E; therefore, the
node G is printed first and then E as shown below:
• Once the traversal of the left part of the node C is traversed, then we
move to the right part of the node C. The right child of node C is node
F. Since F is also a root node for the nodes H and I; therefore, the left
child 'H' is traversed first and then the right child 'I' of node F as
shown below:
• After traversing H and I, node F is traversed as shown below:

Once the left part and the right part of node C are traversed,
then the node C is traversed as shown below:
• In the above tree, the left subtree and the right subtree of root node
A have been traversed, the node A would be traversed.
Tress Traversal
OUTPUT
• Inorder traversal
• 8 ->9 ->7 ->10 ->11 ->12 ->13 ->
• Preorder traversal
• 10 ->9 ->8 ->7 ->12 ->11 ->13 ->
• Postorder traversal
• 8 ->7 ->9 ->11 ->13 ->12 ->10 ->
Application: Expression Evaluation.

• Expression Tree
• The expression tree is a binary tree in which each internal node
corresponds to the operator and each leaf node corresponds to the
operand so for example expression tree for 3 + ((5+9)*2) would be:

• Inorder traversal of expression tree produces infix version of given
postfix expression (same with postorder traversal it gives postfix
expression)
Construction of Expression Tree:
• Now For constructing an expression tree we use a stack. We loop
through input expression and do the following for every character.
1.If a character is an operand push that into the stack
2.If a character is an operator pop two values from the stack make
them its child and push the current node again.
• In the end, the only element of the stack will be the root of an
expression tree.
Evaluation of Expression Tree

• Given a simple expression tree, consisting of basic binary operators


i.e., + , – ,* and / and some integers, evaluate the expression tree.
• Examples:
• Input :
• Root node of the below tree
Output :
100
• Input :
• Root node of the below tree

Output :
110
• As all the operators in the tree are binary hence each node will have
either 0 or 2 children. As it can be inferred from the examples above,
the integer values would appear at the leaf nodes, while the interior
nodes represent the operators.
Graph

• A graph can be defined as group of vertices and edges that are used
to connect these vertices. A graph can be seen as a cyclic tree, where
the vertices (Nodes) maintain any complex relationship among them
instead of having parent child relationship.
Definition

• A graph G can be defined as an ordered set G(V, E) where V(G)


represents the set of vertices and E(G) represents the set of edges
which are used to connect these vertices.
• A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B),
(B,C), (C,E), (E,D), (D,B), (D,A)) is shown in the following figure.
Directed and Undirected Graph

• A graph can be directed or undirected. However, in an undirected


graph, edges are not associated with the directions with them. An
undirected graph is shown in the above figure since its edges are not
attached with any of the directions. If an edge exists between vertex
A and B then the vertices can be traversed from B to A as well as A to
B.
• In a directed graph, edges form an ordered pair. Edges represent a
specific path from some vertex A to another vertex B. Node A is called
initial node while node B is called terminal node.
A directed graph is shown in the following figure.
Graph Terminology

• 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.
Graph Representation

• By Graph representation, we simply mean the technique which is to


be used in order to store some graph into the computer's memory.
• There are two ways to store Graph into the computer's memory.
1. Sequential Representation

• In sequential representation, we use adjacency matrix to store the


mapping represented by vertices and edges. In adjacency matrix, the
rows and columns are represented by the graph vertices. A graph
having n vertices, will have a dimension n x n.
• An entry Mij in the adjacency matrix representation of an undirected
graph G will be 1 if there exists an edge between Vi and Vj.
• An undirected graph and its adjacency matrix representation is shown
in the following figure.
• in the above figure, we can see the mapping among the vertices (A, B,
C, D, E) is represented by using the adjacency matrix which is also
shown in the figure.
• There exists different adjacency matrices for the directed and
undirected graph. In directed graph, an entry Aij will be 1 only when
there is an edge directed from Vi to Vj.
• A directed graph and its adjacency matrix representation is shown in
the following figure.
• Representation of weighted directed graph is different. Instead of
filling the entry by 1, the Non- zero entries of the adjacency matrix
are represented by the weight of respective edges.
• The weighted directed graph along with the adjacency matrix
representation is shown in the following figure.
Linked Representation

• In the linked representation, an adjacency list is used to store the


Graph into the computer's memory.
• Consider the undirected graph shown in the following figure and
check the adjacency list representation.
• An adjacency list is maintained for each node present in the graph
which stores the node value and a pointer to the next adjacent node
to the respective node. If all the adjacent nodes are traversed then
store the NULL in the pointer field of last node of the list.
• Consider the directed graph shown in the following figure and check
the adjacency list representation of the graph.
• In a directed graph, the sum of lengths of all the adjacency lists is
equal to the number of edges present in the graph.
• In the case of weighted directed graph, each node contains an extra
field that is called the weight of the node. The adjacency list
representation of a directed graph is shown in the following figure.
Graph Traversal Algorithm

• The techniques by using which, we can traverse all the vertices of the
graph.
• Traversing the graph means examining all the nodes and vertices of
the graph. There are two standard methods by using which, we can
traverse the graphs. Lets discuss each one of them in detail.
• Breadth First Search
• Depth First Search
Breadth First Search (BFS) Algorithm

• Breadth first search is a graph traversal algorithm that starts


traversing the graph from root node and explores all the neighboring
nodes. Then, it selects the nearest node and explore all the
unexplored nodes. The algorithm follows the same process for each
of the nearest node until it finds the goal.
• The algorithm of breadth first search is given below. The algorithm
starts with examining the node A and all of its neighbors. In the next
step, the neighbors of the nearest node of A are explored and process
continues in the further steps. The algorithm explores all neighbors of
all the nodes and ensures that each node is visited exactly once and
no node is visited twice
C Program for Breadth First Search
#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v) {
for (i=1;i<=n;i++)
if(a[v][i] && !visited[i])
q[++r]=i;
if(f<=r) {
visited[q[f]]=1;
bfs(q[f++]);
}
}
void main() {
int v;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for (i=1;i<=n;i++) {
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The node which are reachable are:\n");
for (i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i); else
printf("\n Bfs is not possible");
getch();
}
Depth First Search (DFS) Algorithm

• Depth first search (DFS) algorithm starts with the initial node of the
graph G, and then goes to deeper and deeper until we find the goal
node or the node which has no children. The algorithm, then
backtracks from the dead end towards the most recent node that is
yet to be completely unexplored.
• The data structure which is being used in DFS is stack. The process is
similar to BFS algorithm. In DFS, the edges that leads to an unvisited
node are called discovery edges while the edges that leads to an
already visited node are called block edges.
C Program for Depth First Search
#include<stdio.h>

void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is
sorted in array G[10][10]
void main()
{
int i,j;
printf("Enter number of vertices:");

scanf("%d",&n);
//read the adjecency matrix
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
//visited is initialized to zero
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}
Connected Component Definition
• A connected component or simply component of an
undirected graph is a subgraph in which each pair of nodes is
connected with each other via a path.
• Let’s try to simplify it further, though. A set of nodes forms a
connected component in an undirected graph if any node
from the set of nodes can reach any other node by traversing
edges. The main point here is reachability.
• In connected components, all the nodes are always
reachable from each other.
One Connected Component
• Let’s name this graph G1(V, E). Here V = \{V1, V2, V3, V4, V5, V6\} denotes the vertex set
and E = \{E1, E2, E3, E4, E5, E6, E7\} denotes the edge set of G1. The graph G1 has one
connected component, let’s name it C1, which contains all the vertices of G1. Now let’s
check whether the set C1 holds to the definition or not.

• According to the definition, the vertices in the set C1 should reach one another via a
path. We’re choosing two random vertices V1 and V6:

• V6 is reachable to V1 via: E4 \rightarrow E7 \ or\ E3 \rightarrow E5 \rightarrow E7 \ or\


E1 \rightarrow E2 \rightarrow E6 \rightarrow E7
• V1 is reachable to V6 via: E7 \rightarrow E4 \ or\ E7 \rightarrow E5 \rightarrow E3 \ or\
E7 \rightarrow E6\rightarrow E2 \rightarrow E1
• The vertices V1 and V6 satisfied the definition, and we could do the same with other
vertex pairs in C1 as well.
More Than One Connected Component

• In this example, the undirected graph has three connected


components:

• Let’s name this graph as G2(V, E), where V = \{V1, V2, V3, V4, V5, V6, V7, V8, V9, V10, V11, V12\},
and E = \{E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11\}. The graph G2 has 3 connected components:
C1 = \{V1, V2, V3, V4, V5, V6\}, C2 = \{V7, V8, V9\} and C3 = \{V10, V11, V12\}.

• Now, let’s see whether connected components C1, C2, and C3 satisfy the definition or not. We’ll
randomly pick a pair from each C1, C2, and C3 set.

• From the set C1, let’s pick the vertices V4 and V6.

• V6 is reachable to V4 via: E2 \rightarrow E6 \rightarrow E7 \ or\ E1 \rightarrow E4 \rightarrow E7


\ or\ E1 \rightarrow E3 \rightarrow E5 \rightarrow E7
• V4 is reachable to V6 via: E7 \rightarrow E6 \rightarrow E2 \ or\ E7 \rightarrow E4 \rightarrow E1
\ or\ E7 \rightarrow E5 \rightarrow E3 \rightarrow E1
• Now let’s pick the vertices V8 and V9 from the set C2.
• V9 is reachable to V8: E9 \rightarrow E8
• V8 is reachable to V9: E8 \rightarrow E9
• Finally, let’s pick the vertices V11 and V12 from the set C3.

• V11 is reachable to V12: E11 \rightarrow E10


• V12 is reachable to V11: E10 \rightarrow E11
• So from these simple demonstrations, it is clear that C1, C2, and C3
follow the connected component definition.
Spanning Tree

• n this topic, we will learn about the spanning tree and minimum spanning tree. Before
knowing about the spanning trees, we should know about some graphs.
• The following are the types of graphs:
• Undirected graph: An undirected graph is a graph in which all the edges do not point to
any particular direction, i.e., they are not unidirectional; they are bidirectional.
It can also be defined as a graph in which set of V vertices and set of E edges, each edge
connecting two different vertices.
• Connected graph: A connected graph is a graph in which a path always exists from a
vertex to any other vertex.
A graph is connected if we can reach any vertex from any other vertex by following edges
in either direction.
• Directed graph: A directed graph is defined as a graph in which set of V vertices and set
of Edges, each connecting two different vertices, but it is not mandatory that node points
in the opposite direction also.
What is a Spanning tree?

• If we have a graph containing V vertices and E edges, then the graph


can be represented as:
• G(V, E)
• If we create the spanning tree from the above graph, then the
spanning tree would have the same number of vertices as the graph,
but the edges are not equal. The edges in the spanning tree would be
equal to the number of edges in the graph minus 1.
• Suppose the spanning tree is represented as:
• G`(V`, E`)
• where,
• V=V`
• E`ϵ E -1
• E`=|V| - 1
• Let's understand through an example.
• Suppose we want to create the spanning tree of the graph, which is
shown below:

• As we know, that spanning tree contains the same number of vertices
as the graph, so the total number of vertices in the graph is 5;
therefore, the spanning tree will also contain the 5 vertices. The
edges in the spanning tree are equal to the number of vertices in the
graph minus 1; therefore, the number of edges is 4. Three spanning
trees can be created, which are shown below:
Minimum Spanning Trees

• The minimum spanning tree is the tree whose sum of the edge
weights is minimum. From the above spanning trees, the total edge
weight of the spanning tree 1 is 12, the total edge weight of the
spanning tree 2 is 14, and the total edge weight of the spanning tree
3 is 11; therefore, the total edge weight of the spanning tree 3 is
minimum. From the above graph, we can also create one more
spanning tree as shown below:
In the above tree, the total edge weight is 10 which is less than
the above spanning trees; therefore, the minimum spanning
tree is a tree which is having an edge weight, i.e., 10.
Properties of Spanning tree
• A connected graph can contain more than one spanning tree. The
spanning trees which are minimally connected or we can say that the
tree which is having a minimum total edge weight would be
considered as the minimum spanning tree.
• All the possible spanning trees that can be created from the given
graph G would have the same number of vertices, but the number of
edges in the spanning tree would be equal to the number of vertices
in the given graph minus 1.
• The spanning tree does not contain any cycle. Let's understand this
property through an example.
• Suppose we have the graph which is given below:

We can create the spanning trees of the above graph, which


are shown below:
As we can observe in the above spanning trees that one edge
has been removed. If we do not remove one edge from the
graph, then the tree will form a cycle, and that tree will not be
considered as the spanning tree.
• The spanning tree cannot be disconnected. If we remove one more edge from any of the above
spanning trees as shown below:
The above tree is not a spanning tree because it is disconnected now.
• If two or three edges have the same edge weight, then there would be more than two minimum
spanning trees. If each edge has a distinct weight, then there will be only one or unique minimum
spanning tree.
• A complete undirected graph can have nn-2 number of spanning trees where n is the number of
vertices in the graph. For example, the value of n is 5 then the number of spanning trees would be
equal to 125.
• Each connected and undirected graph contains at least one spanning tree.
• The disconnected graph does not contain any spanning tree, which we have already discussed.
• If the graph is a complete graph, then the spanning tree can be constructed by removing
maximum (e-n+1) edges. Let's understand this property through an example.
A complete graph is a graph in which each pair of vertices are connected. Consider the complete
graph having 3 vertices, which is shown below:
We can create three spanning trees from the above graph
shown as below:
• According to this property, the maximum number of edges from the
graph can be formulated as (e-n+1) where e is the number of edges, n
is the number of vertices. When we substitute the value of e and n in
the formula, then we get 1 value. It means that we can remove
maximum 1 edge from the graph to make a spanning tree. In the
above spanning trees, the one edge has been removed.
Applications of Spanning trees
• The following are the applications of the spanning trees:
• Building a network: Suppose there are many routers in the network
connected to each other, so there might be a possibility that it forms
a loop. So, to avoid the formation of the loop, we use the tree data
structure to connect the routers, and a minimum spanning tree is
used to minimally connect them.
• Clustering: Here, clustering means that grouping the set of objects in
such a way that similar objects belong to the same group than to the
different group. Our goal is to divide the n objects into k groups such
that the distance between the different groups gets maximized.
• How can clustering be achieved?
• First, we divide the n objects into k groups.
• Secondly, we will combine these clusters iteratively by adding an edge
between them.
• Stop when we reach the k clusters.
• Approach
• One of the approaches that can be used to obtain clustering is to
compute a minimum spanning tree. The minimum spanning tree can
be simply calculated by dropping the k-1 most heavily weighted edge
from the graph.

You might also like