Unit - V DS
Unit - V DS
Unit - V DS
UNIT – V
Trees and Graphs
5.1 Trees:
5.1.1 Basic tree concepts
A tree consists of a finite set of elements called nodes, and a finite set of
directed lines, called branches, that connect the nodes
The number of branches associated with a node is the degree of the node
When the branch is directed toward the node, it is an indegree branch; when the
branch is directed away from the node, it is an outdegree branch
The sum of the indegree and outdegree branches is the degree of the ndoe
A tree consists of a finite set of elements, called nodes, and a finite set of
directed lines, called branches, that connect the nodes
If the tree is not empty, the first node is called the root. The indegree of the
root is, by definition, zero
The indegree of the root is, by definition, zero
With the exception of the root, all of the nodes in a tree must have an indegree
of exactly one; that is they may have only one predecessor
All nodes in the tree can have zero, one, or more branches leaving them; that I,
they may have an outdegree of zero, one, or more(zero or more successors)
Fig. is a representation of a tree
Terminology
In addition to root, many different terms are used to describe the attributes of a
tree
1
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
A leaf is any node with an outdegree of zero, that is, a node with no successors
A node that is not a root or a leaf is known as an internal node because it is
found in the middle portion of a tree
A node is a parent if it has successor nodes that
is if it has an outdegree greater than zero
Conversely, a node with a predecessor is a child
A child has an indegree of one
Two or more nodes with the same parent are siblings
An ancestor is any node in the path from root to the node
An descendent is any node in the path below the parent node; that is, all nodes
in the paths from a give node to a leaf are descendents of that node
Fig. shows the usage of these terms
A path is a sequence of nodes in which each node is adjacent to the next one
Every node in the tree can be reached by following a unique path starting from
the root
In fig. the path form the root to the leaf I is designated as AFI
It includes two distinct branches, AF and FI
The level of a node is its distance from the root
Because the root has a zero distance from itself, the root is at level 0
The children of the root are at level 1, their children at level 2, and soforth
Note the relationships between levels and siblings and in fig. above
Siblings are always at the same level but all nodes in a level are no necessarily
siblings
For ex, at level2 C and D are siblings, as are G, H and I
However D and G are not siblings because they have different parents
The height of the tree is the level of the leaf in the longest path from the root +
2
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
1
By definition the height of the empty tree is -1
Fig. above contains nodes at three levels 0,1, and 2
Its height is 3
Because the tree is drawn upside down, some texts refer to the depth of a tree
rather than its height
The level of a node is its distance from the root. The height of a tree is the
level of the leaf in the longer path from the root plus 1
A tree may be divided into subtrees
A subtree is any connected structure below the root
The first node in a subtree is known as the root of the subtree and is used to
name the subtree
Subtrees can also be further divides into subtees
In fig below, BCD is a subtree as are E and FGHI
Note that by this, a single node is a subtree
Thus, the subtree B can be divided into two subtrees C and D, and the subtree F
contains the subtrees G, H and I
2. Indented list
You will find this used in bill of materials systems in which a parts list
represents the assembly structure of an item
In fig. above clearly shows the relationship among the various components of a
computer, but graphical representations are not easily generated from a database
syste,
The bill – of – materials format was created to show the same information using
a textual parts list format
In a bill of materials, each assembly component is shown indented below to
assembly
Some bills of materials even show the level number of each component
Because a bill of materials shows which components are assembled into each
assembly it is sometimes called a goezinto(goesinto) list
Table shows the computer bill of materials in an indented parts list format
3. Parenthetical listing
4
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
The subtrees are designated as the left subtree and right subtree
Fig. shows a binary tree with its two subtrees
Note that each subtree is itself a binary tree
Fig. above contains eight binary trees; the first of which is a null tree
A null tree is a tree with no nodes, as shown in fig(a)
A node in a binary tree can have no more than two subtrees
Properties
Several properties for binary trees that distinguish them from general trees
Height of binary trees
6
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
Balance
The distance of a node from the root determines how efficiently it can be
located
The children of any node in a tree can be accessed by following only one
branch path, the one that leads to the desired node
The nodes at level 1, which are children of the root, can be accessed by
following only two branches from the root
It stands to reason, therefore, that the sorter the tree, the easier it is to locate any
desired node in the tree
The concept leads us to a very important characteristic of a binary tree – its
balance
To determine whether a tree is balanced, we calculate its balance factor
The balance factor of a binary tree is the difference in height between its left
and right subtrees
If we define the height of the left subtree as HL and the height of the right
subtree as HR, the balance factor of the tree, B, is determined by the following:
B=HL - HR
Using this formula, the balances of the eight trees in fig are a. 0 by definition b.
0, c. 1, d. -1, e. 0, f. 1, g. 2, and h.2
In a balanced binary tree, the height of its subtree differs by no more than
one(its balance factor is -1, 0, or +1), and its subtrees are also balanced
Complete and Nearly complete binary trees
A complete tree has the maximum number of entries for its height(see Nmax in
“height of binary trees”)
The maximum number is reached when the last level is full, see fig.
A tree is considered nearly complete if it has the minimum height for its
nodes(see formula Hmin) and all nodes in the last level are found on the left
Complete and nearly complete trees are shown in fig.
8
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
9
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
To demonstrate the different traversal sequences for a binary tree we use fig
Algorithm preorder(root)
Traverse a binary tree in node – left – right sequence
Pre root is the entry node of a tree of subtree
Post each node has been processed in order
10
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
In the preorder traversal we process the node when we meet it for the first time
This is shown as a black box on the left of the node
The path is shown as a line following a route completely around the tree and
back to the root
Fig. next shows the recursive algorithmic traversal of the tree
11
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
Inorder Traversal(LNR):
The inorder traversal processes the left subtree first, then the root, and finally
the right subtree
The meaning of the prefix in is that the root is processed in between the
subtrees
Once again we implement the algorithm recursively, as shown below
Algorithm Inorder(root)
Traverse a binary tree in left – node – right sequence
Pre root is the entry node of a tree of subtree
Post each node has been processed in order
1. If(root is not null)
1. Inorder(leftsubtree)
2. Process(root)
3. Inorder(rightsubtree)
2. End if
End Inorder
Because the left subtree must be processed first, we trace from the root to the
far left leaf node before processing any node
After processing the left subtree, C, we process its parent node, B
12
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
To walk around the tree in inorder sequence, we follow the same path but
process each node when we meet it for the second time
The processing route is shown in fig(b)
In the inorder traversal, the root is processed between its subtrees
Post order traversal(LRN)
The last of the standard traversal is the postorder traversal
It processes the root node after (Post) the left and right subtrees have been
processed
It starts by locating the far – left leaf and processing it
It then processes its right sibling including its subtrees(if any). Finally it process
the root node
In the postorder traversal, the root is processed after its subtrees
The recursive postorder traversal logic is shown in algorithm
Algorithm postorder(root)
Traverse a binary tree in left– right – node sequence
Pre root is the entry node of a tree of subtree
Post each node has been processed in order
1. If(root is not null)
1. Postorder(leftsubtree)
2. Postorder(rightsubtree)
3. Process(root)
13
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
2. End if
End postorder
In the tree walk for a postorder traversal we move the processing block to the
right of the node so that we process it as we meet the node for the third time
The postorder traversal is shown in fig.
Note that we took the same path in all three walks; only the time of the
processing changed
Algorithm breadthfirst(root)
Process tree using breadth first traversal
Pre root is node to be processed
Post tree has been processed
1. Set current node to root
2. Createqueue(bfqueue)
3. Loop(current node not null)
1. Process(current node)
2. If(left subtree not null)
1. Enqueue(bfqueue, leftsubtree)
3. End if
14
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
15
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
Infix traversal
We write algorithm, when we print the infix expression tree, we must add an
opening parenthesis at the beginning of each expression and a closing
parenthesis at the end of each expression
Because the root of three and each of its subtrees represents a sub expression,
we print the opening when we start tree or a subtree and the closing parenthesis
when we have processed all of its children
Fig. shows the placement of parenthesis as we walk through the tree using an
inorder traversal
16
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
Algorithm infix(tree)
Print the infix expression for an expression tree
Pre tree is a pointer to an expression tree
Post the infix expression as been printed
1. if(tree not empty)
1. if(tree token is an operand)
1. print(tree – token)
2. else
1. print(open parenthesis)
2. infix(tree left subtree)
3. print(tree – token)
4. infix(tree right subtrree)
5. print(close parenthesis)
3. end if
2. end if
end infix
Postfix traversal
The expression uses the basic post order traversal of an binary tree
Note that it does not require parentheses
The pseudo code is shown in algorithm
Algorithm postfix(tree)
Print the postfix expression for an expression tree
17
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
Prefix traversal
The final expression tree traversal is the prefix traversal
It uses the standard preorder tree traversal
Again, no parentheses are necessary
The pseudo code is shown in algorithm
Algorithm prefix(tree)
Print the prefix expression for an expression tree
Pre tree is a pointer to an expression tree
Post the prefix expression has been printed
1. if(tree not empty)
1. print(tree token)
2. prefix(tree left subtree)
3. prefix(tree right subtree)
2. end if
end prefix
19
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
20
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
If we traverse the tree using a preorder traversal, we get the results shown
below
23 18 12 20 44 35 52
Although this traversal is valid, it is not very useful
Let’s try a postorder traversal and see if it is more useful
12 20 18 35 52 44 23
Inorder traversal produces a sequenced list,
12 18 20 23 35 44 52
b. Searches
Three searches algorithms:
21
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
Algorithm findsmallestBST(root)
This algorithm finds the smallest node in a BST
Pre root is a pointer to a nonempty BST or subtree
Return address of smallest node
1. if(left subtree empty)
1. return(root)
2. end if
3. return findsmallestBST(left subtree)
end findsmallestBST
Algorithm findlargestBST(root)
This algorithm finds the largest node in a Binary search tree
Pre root is a pointer to a nonempty Binary search tree or subtree
Return address of largest node returned
1. if(right subtree empty)
22
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
1. return(root)
2. end if
3. return findlargestBST(right subtree)
end findlargestBST
3. BST search
The binary tree search locates a specific node in the tree
To understand, we recall binary search algorithm, is shown in fig.
The fig. traces each of the possible search paths from the middle element in the
array
Starting with 23, the binary search examines either 18 or 44 depending on the
search key
From 18 it examines either 12 or 20, from 44 it examines either 35 or 52
As is clear in fig, tracing all possible search paths follows the same paths we
see in a binary search tree
subtree
We go right and find our desired value
This logic is shown in algorithm
24
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
c. Insertion
The insert node function adds data to a Binary search tree to insert a data all we
need to do is follow the branches to an empty subtree and then insert the new
node
Insertion takes place at a leaf like node, a node that has only one subtree
All Binary search tree insertions takes place at a leaf or a leaf like node
Fig. shows our binary search tree after we have inserted two nodes
d. Deletion
To delete a node from a binary search tree, we must first locate it
There are four possible cases when we delete a node:
26
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
28
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
For ex, given a network of computers, we can create a tree that connects all of
the computers
The minimum spanning tree gives us the shortest length of cable that can be
used to connect all computers ensuring that there is a path between any two
computers
A spanning tree contains all of the vertices in a graph. A minimum spanning
tree is a spanning tree in which total weight of the lines is guaranteed to be the
minimum of all possible trees in the graph
To create a minimum spanning tree in a strongly connected network that is, in a
29
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
network in which there is a path between any two vertices – the edges for the
minimum spanning tree are chosen so that the following properties exist:
1. Every vertex is included
2. The total edge weight of the spanning tree is the minimum possible that
includes a path between any two vertices
Minimum spanning tree example is in Fig.
Data Structure:
graph head
count
first
end graphhead
graph vertex
next vertex
30
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
data
indegree
outdegree
intree
first edge
end graphvertex
graphedge
destination
weight
next edge
intree
end graphedge
Minimum spanning tree pseudocode
Algorithm spanningtree(graph)
Determine the minimum spanning tree of a network
Pre graph contains a network
Post spanning tree determined
1. if(empty graph)
1. return
2. end if
3. loop(through all vertices)
set intree flags false
1. set vertex intree flag to false
2. loop(through all edges)
1. set edge intree flag to false
2. get next edge
3. end loop
4. get next vertex
4. end loop
now derive spanning tree
5. set first vertex to intree
6. set tree to complete to false
7. loop(not treecomplete)
1. set tree complete to tree
2. set minedge to maximum integer
3. set minedgeloc to null
4. loop(through all vertices)
walk through graph checking vertices in tree
1. if(vertex intree AND vertex outdegree > 0)
31
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
5.2.Graphs
In the graph each node may have multiple predecessors as well as multiple
successors
Graphs are very useful structures
They can be used to solve complex routing problems, such as designing an
routing airlines among the airports they serve
5.2.1 Introduction
A graph is a collection of nodes, called vertices, and a collection of segments,
called lines, connecting pairs of vertices
In other words, a graph consists of two sets, a set of vertices and a set of lines
Graphs may be either directed or undirected
A directed graph or digraph for short, is a graph in each line has a
direction(arrow head) to its successor
The lines in a directed graph are known as arcs
An undirected graph is a graph in which there is no direction on any of the
lines, which are known as edges
Fig contains an example of both a directed graph (a) and an undirected graph
32
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
(b)
A path is a sequence of vertices in which each vertex is adjacent to the next one
In fig. {A, B, C, E} is one path and {A, B, E, F} is another
Note that is both directed(you may travel in indicated direction) and undirected
graph(you may travel in either direction) have paths
Two vertices in a graph are said to be adjacent vertices (or neighbors) if there is
a path length 1 connecting them
In fig(a) B is adjacent to A, whereas E is not adjacent to D; on the other hand, D
is adjacent to E
In fig(b), E and D are adjacent, but D and F are not
A cycle is a path consisting of atleast three vertices that starts and ends with the
same vertex
In fig(b) B, C, D, E, B is a cycle
The same vertices in fig(a) is not a cycle
A loop is a special case of a cycle in which a single arc begins and ends with
the same vertex
In a loop the end points of the line are the same
33
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
5.2.2 Operations
34
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
Six primitive graph operations that provide the basic modules needed to
maintain a graph
- Insert a vertex
- Delete a vertex
- Add an edge
- Delete an edge
- Find a vertex
- Traverse a graph
Insert a vertex
It adds a new vertex to a graph
When it is inserted, it is disjoint; that is, it is not connected to any other vertices
in the list
Inserting a vertex is just the first step in the insertion process
After insertion, it must be connected
Fig. shows a graph before and after a new vertex is added
Delete a vertex
Delete vertex removes a vertex from the graph
When a vertex is deleted, all connecting edges are also removed
Fig shows deleting a vertex
35
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
Add edge
Add edge connects a vertex to a destination vertex
If a vertex requires multiple edges, add an edge must be called once for each
adjacent vertex
To add an edge, two vertices must be specified
If the graph is a digraph, one of the vertices must be specified as the source and
one as the destination
Fig shows an examples of adding an edge {A, E}, to the graph
Delete Edge
Delete edge removes one edge from a graph
Fig. shows an example that deletes the edge {A, E} from the graph
Find vertex
Find vertex traverses a graph, looking for a specified vertex
36
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
37
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
The depth first traversal of a graph starts by processing the first vertex of the
graph
After processing the first vertex, we select any vertex adjacent to the first vertex
and process it
We process each vertex, we select an adjacent vertex until we reach a vertex
with no adjacent entries
The logic requires a stack (recursion) to complete the traversal
The traversal processes adjacent vertices in descending, or last – in – first out
(LIFO) order
Trace a DFT through a graph in fig.
The number in the box next to a vertex indicates the processing order
The stacks below the graph show the stack contents as we work our way down
the graph and then as we back out
1. We begin by pushing the first vertex A, into the stack
2. We then loop, pop the stack, and, after processing the vertex, push all of the
adjacent vertices into the stack, process it and then push G and into the
stack, giving the stack contents for step 3 as shown in fig (B) – HG
3. When the stack is empty the traversal is complete
38
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
We show that the BFT uses a queue of its adjacent vertices in the queue
Then select the next vertex to be processed, we delete a vertex from the queue
and process it
Lets trace the graph in fig.
40
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
If vertices are adjacent – that is, if there is an edge between them – the matrix
intersect has a value of 1; if there is no edge between them, the intersect is set to
0.
If the graph is directed, the intersection in the adjacency matrix indicates the
direction
For ex, if fig(b) there is an arc from source vertex B to destination vertex C
In the matrix, this is arc is seen as 1, in the intersection from B (on the left) to C
(on the top)
Because there is no arc from C to B
The intersection from C to B is 0
In fig(a) the edge from B to C is bidirectional that is you can traverse in either
direction
So, from B to C is 1 as well as C to B is also 1
The matrix reflects the fact that you can use the edge to go either way.
The vertex list is a singly linked list of the vertices in the list
It could be implemented using a doubly or circularly linked lists
The pointer at the left of the list links the vertex entries
The pointer at the left of the list links the vertex entries
The pointer at the right in the vertex is a head pointer to a linked list of edges
from the vertex
Thus, in the nondirected graph on the left in fig, there is a path from vertex B to
vertex A, C, and E
To find these edges in the adjacency list, we start at B’s vertex list entry and
traverse the linked list to A, then to C, and finally to E
In the adjacency list, we use a linked list to store the vertices an a 2 – D linked list
to store the arcs
c. Delete Vertex
To delete a vertex first we need to find it
Once we have found it, we need to make sure that is disjoint; that is, we need to
ensure that there are no arcs leaving or entering the vertex
If there are, we reject the deletion
Algorithm deletevertex(graph, key)
Deletes an existing vertex only if its degree is 0
Pre graph is a reference pointer to graph head
key is the key of the vertex to be deleted
43
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
d. Insert arc
Insert arc requires two points in the graph: the source vertex (fromptr) and the
destination vertex (toptr)
Each is identified by its key value rather than by its physical address
Algorithm insertArc(graph, fromkey, tokey)
Adds an arc between two vertices
Pre graph is reference to graph head structure
fromkey is the key of the originating vertex
tokey is the key of the destination vertex
Post arc added to adjacency list
Return +1 if successful
-2 if fromkey not found
-3 if tokey not found
1. allocate memory for new arc
2. search and set from vertex
3. if(from vertex not found)
1. return -2
44
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
4. end if
5. search and set to vertex
6. if(tovertex not found)
1. return -3
7. end if
8. increment from vertex outdegree
9. increment tovertex indegree
10.set destination to tovertex
11.if(fromvertex arc list empty)
1. set fromvertex firstarc to newarc
2. set newarc nextarc to null
3. return 1
12.end if
13.find insertion point in arc list
14.if(insert at beginning of arc list)
1. set from vertex first arc to newarc
15.else
1. insert in arclist(adjacency list)
16.end if
17.return 1
end insertarc
e. Delete Arc
It removes one arc from the adjacency list
To identify an arc, we need to vertices
The vertices are identified by their key
The algorithm therefore searches the vertex list for the start vertex and then
searches its adjacency list for the destination vertex
After locating and deleting the arc, the degree in the form and to vertices is
adjusted and the memory recycles
Algorithm deleteArc(graph, fromkey, tokey)
Delete arc between two vertices
Pre graph is reference to a graph head structure
fromkey is the key of the originating vertex
tokey is the key of the destination vertex
Post vertex deleted
Return +1 if successful
-2 if fromkey not found
-3 if key not found
45
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
1. if(empty graph)
1. return -2
2. end if
3. search and set fromvertex tovertex with key equal to fromkey
4. if(fromvertex not found)
1. return -2
5. end if
6. if(fromvertex arc list null)
1. return -3
7. end if
8. search and find arc with key equal to tokey
9. if(tokey not found)
1. return -3
10.end if
11.set tovertex to arc destination
12.delete arc
13.decrement fromvertex outdegree
14.decrement tovertex indegree
15.return 1
end deletearc
f. Retrieve Vertex
Retrieve vertex returns the data stored in a vertex
Given the key of the vertex, the data are placed in the output area specified in
the call
Algorithm retrievevertex(graphkey, dataout)
Data contained in vertex is identified by key passed to caller
Pre graph is reference to a graph head structure
key is the key of the vertex data
dataout is reference todata variable
Post vertex data copied to dataout
Return +1 if successful
-2 if key not found
1. if(empty graph)
1. return -2
2. end if
3. search for vertex
4. if(vertex found)
1. move locnptr data to dataout
46
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
2. return 1
5. else
1. return -2
6. end if
end retrievevertex
Algorithm breadthfirst(graph)
Processes the keys of the graph in breadth – first order
Pre graph is pointer to graph head structure
Post vertices processed
1. if(empty graph)
1. return
2. end if
first set all processed flags to not processed
3. createqueue(queue)
4. loop(through all vertices)
1. set vertex to not procesed
5. end loop
48
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
I. Destroy graph
The arcs are deleted when the corresponding vertex is deleted
Algorithm destroygraph(graph)
Traverses graph deleting all vertices and arcs
Pre nothing
Post all vertices and arcs deleted
1. if(empty graph)
1. return
2. loop(more vertices)
49
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR
Data structures Lecture Notes Unit - V
50
Prepared by: T. Sunil Kumar Reddy Assoc. Prof., / G. B. Hima Bindu, Asst. Prof., Dept. of CSE & IT, SVCET,
CTR