UNIT 6 Tree and Graphs
UNIT 6 Tree and Graphs
6.1 Definition
- A graph G = (V, E) consists of V, a nonempty set of vertices (or nodes) and E, a set of edges.
- Each edge has either one or two vertices associated with it, called its endpoints.
- An edge is said to connect its endpoints.
- The set of vertices V of a graph G may be infinite.
- A graph with an infinite vertex set or an infinite number of edges is called an infinite graph,
and in comparison, a graph with a finite vertex set and a finite edge set is called a finite
graph.
EXAMPLE:
1
In the above graph,
V = {a, b, c, d, e}
E = {(a, b), (a, c), (b, d), (c, d), (d, e)}
Types of Graphs
Simple Graphs
- A graph in which each edge connects two different vertices and where no two edges
connect the same pair of vertices is called a simple graph.
Multigraphs
- Graphs that may have multiple edges connecting the same vertices are called multigraphs.
2
Pseudographs
- The edges that connect a vertex to itself, such edges are called loops.
- Graphs that may include loops, and possibly multiple edges connecting the same pair of
vertices or a vertex to itself, are sometimes called pseudographs.
Directed Graphs
- A directed graph (or digraph) (V, E) consists of a nonempty set of vertices V and a set of
directed edges (or arcs) E.
- Each directed edge is associated with an ordered pair of vertices.
- The directed edge associated with the ordered pair (u, v) is said to start at u and end at v.
3
Directed Multigraph
- Directed graphs that may have multiple directed edges from a vertex to a second (possibly
the same) vertex are called directed multigraphs.
- When there are m directed edges, each associated to an ordered pair of vertices (u, v),
we say that (u, v) is an edge of multiplicity m.
Mixed Graph
- A graph with both directed and undirected edges is called a mixed graph.
Graph Models
Graphs are used in a wide variety of models.
➢ Social Networks
➢ Communication Networks
➢ Information Networks
➢ Software Design Applications
➢ Transportation Network
➢ Biological Networks and
➢ Tournaments
Graph Terminologies
Adjacent Vertices and Incident Edges
- Two vertices u and v in an undirected graph G are called adjacent (or neighbours) in G if
u and v are endpoints of an edge e of G.
- Such an edge e is called incident with the vertices u and v and e is said to connect u and v.
Neighbourhood Vertices
- The set of all neighbours of a vertex v of G = (V, E), denoted by N (v), is called
the neighbourhood of v.
- If A is a subset of V, we denote by N (A) the set of all vertices in G that are adjacent to at
least one vertex in A.
- So, 𝑁 (𝐴) = ⋃𝑣∈𝐴 𝑁 (𝑣).
Degree of a Vertix
- The degree of a vertex in an undirected graph is the number of edges incident with it,
except that a loop at a vertex contributes twice to the degree of that vertex.
- The degree of the vertex v is denoted by deg(v).
EXAMPLE: What are the degrees and what are the neighbourhoods of the vertices in the
graphs G and H displayed in figure below.
4
Fig: The Undirected Graphs G and H.
Solution:
- In G, deg(a) = 2, deg(b) = deg(c) = deg(f ) = 4, deg(d ) = 1, deg(e) = 3, and deg(g) = 0.
- The neighbourhoods of these vertices are N (a) = {b, f }, N (b) = {a, c, e, f }, N (c) = {b,
d, e,f }, N (d) = {c}, N (e) = {b, c, f }, N (f ) = {a, b, c, e}, and N (g) = ∅.
- In H, deg(a) = 4, deg(b) = deg(e) = 6, deg(c) = 1, and deg(d ) = 5.
- The neighbourhoods of these vertices are N (a) = {b, d, e}, N (b) = {a, b, c, d, e}, N (c) =
{b},N (d) = {a, b, e}, and N (e) = {a, b, d}.
Isolated and Pendant Vertices
- A vertex of degree zero is called isolated.
- It follows that an isolated vertex is not adjacent to any vertex.
- Vertex g in graph G in Example above is isolated.
- A vertex is pendant if and only if it has degree one.
- Consequently, a pendant vertex is adjacent to exactly one other vertex.
- Vertex d in graph G in Example above is pendant.
5
Fig: The Directed Graph G.
Solution:
- The in-degrees in G are deg−(a) = 2, deg−(b) = 2, deg−(c) = 3, deg−(d) = 2, deg−(e) = 3,
and deg−(f ) = 0.
- The out-degrees are deg+(a) = 4, deg+(b) = 1, deg+(c) = 2, deg+(d) = 2, deg+(e) = 3,
and deg+(f ) = 0.
Cycles
- A cycle Cn, n ≥ 3, consists of n vertices v1, v2,..., vn and edges {v1, v2}, {v2, v3},...,{vn−1,
vn}, and {vn, v1}.
6
Fig: The Cycles C3, C4, C5, and C6.
Wheels
We obtain a wheel Wn when we add an additional vertex to a cycle Cn, for n ≥ 3, and connect
this new vertex to each of the n vertices in Cn, by new edges.
n-Cubes
- An n-dimensional hypercube, or n-cube, denoted by Qn, is a graph that has vertices
representing the 2n bit strings of length n.
- Two vertices are adjacent if and only if the bit strings that they represent differ in exactly
one bit position.
Bipartite Graphs
- A simple graph G is called bipartite if its vertex set V can be partitioned into two disjoint
sets V1 and V2 such that every edge in the graph connects a vertex in V1 and a vertex in V2
(so that no edge in G connects either two vertices in V1 or two vertices in V2).
- When this condition holds, we call the pair (V1, V2) a bipartition of the vertex set V of G.
7
Solution:
- Graph G is bipartite because its vertex set is the union of two disjoint sets, {a, b, d} and {c,
e, f, g}, and each edge connects a vertex in one of these subsets to a vertex in the other
subset.
Subgraph
- A subgraph of a graph G = (V, E) is a graph H = (W, F), where W ⊆ V and F ⊆ E. A
subgraphH of G is a proper subgraph of G if H = G.
- Let G = (V, E) be a simple graph. The subgraph induced by a subset W of the vertex set V
is the graph (W, F), where the edge set F contains an edge in E if and only if both endpoints
of this edge are in W.
- The union of two simple graphs G1 = (V1, E1) and G2 = (V2, E2) is the simple graph
with vertex set V1 𝖴 V2 and edge set E1 𝖴 E2. The union of G1 and G2 is denoted by G1
𝖴 G2.
Representing Graphs
Adjacency lists
- Specify the vertices that are adjacent to each vertex of the graph.
8
EXAMPLE:
Adjacency Matrices
- The adjacency matrix A (or AG) of G, with respect to this listing of the vertices, is the n x
n zero–one matrix with 1 as its (i, j)th entry when vi and vj are adjacent, and 0 as its (i, j)th
entry when they are not adjacent.
- In other words, if its adjacency matrix is A = [aij], then
Incidence Matrices
- Another common way to represent graphs is to use incidence matrices.
- Let G = (V, E) be an undirected graph.
- Suppose that v1, v2,..., vn are the vertices and e1, e2,...,em are the edges of G.
- Then the incidence matrix with respect to this ordering of V and E is the n × m matrix M =
[mij], where
EXAMPLE: Represent the graph shown in figure below with an incidence matrix.
Solution: The incidence matrix is
9
Isomorphism of Graphs
- The simple graphs G1 = (V1, E1) and G2 = (V2, E2) are isomorphic if there exists a one-
to- one and onto function f from V1 to V2 with the property that a and b are adjacent in
G1 if and only if f(a) and f(b) are adjacent in G2, for all a and b in V1.
- Such a function f is called an isomorphism.
- Two simple graphs that are not isomorphic are called nonisomorphic.
EXAMPLE: Show that the graphs G = (V, E) and H = (W, F), displayed in Figure below,
are isomorphic.
Solution:
- The function f with f(u1) = v1, f(u2) = v4, f(u3) = v3, and f (u4) = v2 is a one-to-one
correspondence between V and W.
- To see that this correspondence preserves adjacency, note that adjacent vertices in G are u1
and u2, u1 and u3, u2 and u4, and u3 and u4, and each of the pairs f (u1) = v1 and f (u2) = v4, f
(u1) = v1 and f (u3) = v3, f (u2) = v4 and f (u4) = v2, and f (u3) = v3 and f (u4) = v2 consists of
two adjacent vertices in H.
Path
- Let n be a nonnegative integer and G an undirected graph.
10
- A path of length n from u to v in G is a sequence of n edges e1,...,en of G for which there
exists a sequence x0 = u, x1,...,xn−1, xn = v of vertices such that ei has, for i = 1,...,n, the end
points xi−1 and xi.
- When the graph is simple, we denote this path by its vertex sequence x0, x1,...,xn (because
listing these vertices uniquely determines the path).
- The path is a circuit if it begins and ends at the same vertex, that is, if u = v, and has length
greater than zero.
- The path or circuit is said to pass through the vertices x1, x2,...,xn−1 or traverse the edges
e1, e2,...,en.
- A path or circuit is simple if it does not contain the same edge more than once.
Connected Components
- A connected component of a graph G is a connected subgraph of G that is not a proper
subgraph of another connected subgraph of G. That is, a connected component of a graph G
is a maximal connected subgraph of G. A graph G that is not connected has two or more
connected components that are disjoint and have G as their union.
11
Euler Paths and Circuits
- An Euler circuit in a graph G is a simple circuit containing every edge of G.
- An Euler path in G is a simple path containing every edge of G.
EXAMPLE: Check whether the given graph is Euler Graph or not.
Shortest-Path Problems
Many problems can be modelled using graphs with weights assigned to their edges. Such as:
➢ Problems involving distances can be modelled by assigning distances between
cities to the edges.
➢ Problems involving flight time can be modelled by assigning flight times to edges.
Weighted Graphs
- Graphs that have a number assigned to each edge are called weighted graphs.
- Weighted graphs are used to model computer networks.
12
- Communications costs (such as the monthly cost of leasing a telephone line), the response
times of the computers over these lines, or the distance between computers, can all be
studied using weighted graphs.
EXAMPLE:
Dijkstra’s Algorithm
– This approach is of getting single source shortest paths.
Algorithm:
Dijkstra(G,w,s)
{
for each vertex v V
do d[v] =
d[s] = 0
S=
Q=V
While(Q!= )
{
u = Take minimum from Q and delete. S
= S {u}
for each vertex v adjacent to u do
if d[v] > d[u] + w(u,v)
13
then d[v] = d[u] + w(u,v)
}
}
EXAMPLE: Find the shortest paths from the source g to all other vertices using Dijkstra’s
algorithm.
Solution:
14
The Traveling Salesperson Problem
A traveling salesperson wants to visit each of n cities exactly once and return to his starting
point.
Planar Graphs
- A graph is called planar if it can be drawn in the plane without any edges crossing (where
a crossing of edges is the intersection of the lines or arcs representing them at a point
other than their common endpoint).
- Such a drawing is called a planar representation of the graph.
EXAMPLE:
15
Graph Colouring
- A colouring of a simple graph is the assignment of a colour to each vertex of the graph so
that no two adjacent vertices are assigned the same colour.
Chromatic number
- The chromatic number of a graph is the least number of colours needed for a colouring of
this graph.
- The chromatic number of a graph G is denoted by χ (G). (Here χ is the Greek letter chi.)
16
Graph Representing Scheduling of Final Exam
6.2 Trees
Definition of
Tree
A tree is a connected undirected graph with no simple circuits.
Tree Terminologies
Suppose that T is a rooted tree.
Root
- The root node is the topmost node in the tree hierarchy.
17
Siblings
- Vertices with the same parent are called siblings.
Ancestors
- The ancestors of a vertex other than the root are the vertices in the path from the root to this
vertex, excluding the vertex itself and including the root (that is, its parent, its parent’s
parent, and so on, until the root is reached).
Descendants
- The descendants of a vertex v are those vertices that have v as an ancestor.
Leaf
- A vertex of a rooted tree is called a leaf if it has no children.
Internal vertices
- Vertices that have children are called internal vertices.
Subtree
- If ‘a’ is a vertex in a tree, the subtree with a as its root is the subgraph of the tree consisting
of ‘a’ and its descendants and all edges incident to these descendants.
18
- The siblings of h are i and j.
- The ancestors of e are c, b, and a.
- The descendants of b are c, d, and e.
- The internal vertices are a, b, c, g, h, and j.
- The leaves are d, e, f, i, k, l, and m.
- The subtree rooted at g is shown in Figure below.
Applications of trees
The following are the 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.
For example, a binary tree has a logN time for searching an element.
• Trie: It is a special kind of tree that is used to store the dictionary. It is a fast and efficient
way for dynamic spell checking.
• Heap: It is also a tree data structure implemented using arrays. It is used to implement
priority queues.
• B tree and B+ tree: B tree and B+ tree are the tree data structures used to implement
indexing in databases.
• Routing table: The tree data structure is also used to store the data in routing tables in the
routers.
Tree Traversals
- The tree traversal is a way in which each node in the tree is visited exactly once in a
symmetric manner.
- There are three popular methods of traversal
• Pre-order traversal
19
• In-order traversal
• Post-order traversal
Pre-order traversal
- The preorder traversal of a nonempty binary tree is defined as follows:
• Visit the root node
• Traverse the left sub-tree in preorder
• Traverse the right sub-tree in preorder
- The preorder is also known as depth first order.
EXAMPLE:
In-order traversal
- The inorder traversal of a nonempty binary tree is defined as follows:
• Traverse the left sub-tree in inorder
• Visit the root node
• Traverse the right sub-tree in inorder
EXAMPLE:
- The inorder traversal output of the given tree is: H D I B E A F C G
Post-order traversal
- The post-order traversal of a nonempty binary tree is defined as follows:
• Traverse the left sub-tree in post-order
• Traverse the right sub-tree in post-order
• Visit the root node
EXAMPLE:
- The post-order traversal output of the given tree is: H I D E B F G C A
20
Spanning Tree
- Let G be a simple graph.
- A spanning tree of G is a subgraph of G that is a tree containing every vertex of G.
EXAMPLE: Find a spanning tree of the simple graph G shown in Figure below.
Solution:
- The graph G is connected, but it is not a tree because it contains simple circuits.
- Remove the edge {a, e}.
- This eliminates one simple circuit, and the resulting subgraph is still connected and still
contains every vertex of G.
- Next remove the edge {e, f} to eliminate a second simple circuit.
- Finally, remove edge {c, g} to produce a simple graph with no simple circuits.
- This subgraph is a spanning tree, because it is a tree that contains every vertex of G.
- The sequence of edge removals used to produce the spanning tree is illustrated in Figure
below.
Fig: Producing a Spanning Tree for G by Removing Edges That Form Simple Circuits.
21
Kruskal’s Algorithm
- To carry out Kruskal’s algorithm, choose an edge in the graph with minimum weight.
Algorithm:
Solution:
22
- The total weight of MST is 64.
Assignment
1. Define Euler path and Hamilton path with examples. [TU 2075]
2. Define spanning tree and minimum spanning tree. Mention the conditions for two
graphs for being isomorphic with an example. (5) [TU 2075]
3. What is meant by chromatic number? How can you use graph colouring to schedule
exams? Justify by using 10 subjects assuming that the pairs {(1,2), (1,5), (1,8), (2,4),
(2,9), (2,7), (3,6), (3,7), (3,10), (4,8), (4,3), (4,10), (5,6), (5,7)} of subjects have
common students. (1+4) [TU Model Question]
4. Define bipartite graph with example. State the necessary conditions for the graphs to
be isomorphic. [TU 2079]
Lab 6
Write a C program to represent relations
Ans: Let A = {3,4,5}, B = {6,7,8} Find relation R on A*B such that x+y<12 where x A and y B
#include<conio.h>
#include<stdio.h>
void createRelation(int A[],int B[],int n1,int n2)
{
printf("{");
for(int i=0;i<n1;i++)
{
for(int j=0;j<n2;j++)
{
if(A[i]+B[j]<13)
{
printf("(%d,%d)",A[i],B[j]);
}
}
}
printf("}");
}
int main()
{
int A[] = {4,5,6};
23
int B[] = {6,7,8,9};
createRelation(A,B,3,4);
getch();
return 0;
}
Output:
{(4,6)(4,7)(4,8)(5,6)(5,7)(6,6)}
Distance of node0=8
Path=0<-4<-1
Distance of node2=5
Path=2<-1
Distance of node3=6
Path=3<-1
Distance of node4=2
Path=4<-1
Write a C program to find minimum spanning tree (Kruskal's Algorithm)
Ans:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
int main()
{
printf("Implementation of Kruskal's algorithm\n");
printf("Enter the no. of vertices\n");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("Enter wt from vertex %d to %d\n",i,j);
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("\nThe edges of Minimum Cost Spanning Tree are\n");
while(ne<n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("\n%d edge (%d,%d) =%d\n",ne++,a,b,min);
28
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\nMinimum cost = %d\n",mincost);
getch();
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}
Output:
Implementation of Kruskal's algorithm
Enter the no. of vertices
5
1 edge (1,5) =1
2 edge (4,5) =1
3 edge (3,5) =2
4 edge (1,2) =3
Minimum cost = 7
30