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

Module 4

Uploaded by

ruksarp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Module 4

Uploaded by

ruksarp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

DATASTRUCTURES AND APPLICATIONS BCS304

MODULE 4

BINARY SEARCH TREE: Binary Search Tree is a binary tree.it may be empty. If it is not
empty then it satisfies the following properties.
1. Each node has exactly one key and keys are distinct.
2. The keys in the left sub-tree are smaller than the key in the root.
3. The keys in the right sub-tree are greater than the key in the root.
4. The left and right sub-tree are also binary search trees.
Example of BST

Searching a Binary Search Tree: Write a recursive C function of a binary Search Tree

element* search(treepointer root,int k){


if(!root)
return NULL
if(k==root->data.key)
return &(root->data);
if(k<root->data.key)
return search(leftchild,k);
return search(rightchild,k);
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

Searching a Binary Search Tree: Write a Iteraive C function of a binary Search Tree

element* search(treepointer root,int k){


while(tree){
if(k==root->data.key)
return &(root->data);
if(k<root->data.key)
tree=tree->leftchild;
else
tree=tree->rightchild;
}
return NULL;
}
Inserting into a BST: construct a BST for the following nodes given
Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

Write a C function for inserting a node into BST


void insert(treepointer *ndoe,int k,iType theItem){
treepointer ptr,temp=search(*node,k);
if(temp || !(*node)){
MALLOC(ptr,sizeof(*ptr);
ptr->data.key =k;
ptr->data.item = theItem;
ptr->leftChild = ptr->rightChild = NULL;
if(*node)
if(k<temp->data.key)
temp->leftChild=ptr;;
else
temp->rightChild=ptr;;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

else
*node=ptr;
}
}
Deleting a node from a BST:

In a binary search tree, we must delete a node from the tree by keeping in mind that the property
of BST is not violated. To delete a node from BST, there are three possible situations occur -

1. The node to be deleted is the leaf node, or,


2. The node to be deleted has only one child, and,
3. The node to be deleted has two children

Case 1: delete a leaf node (90):

After deletion tree look like this:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

Case 2: delete a node which contains one leaf(79): in place of parent node leaf node will be
replaced.

After deleting a parent node having one child tree look like as follows.

Case 3: Delete a node which contains two children (45):

 First, find the inorder successor of the node to be deleted.


 After that, replace that node with the inorder successor until the target node
is placed at the leaf of tree.
OR

 First, find the inorder predecessor of the node to be deleted.


 After that, replace that node with the inorder predecessor until the target node
is placed at the leaf of tree.
Example

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

Inorder treversal of the above tree is : 10 15 20 45 55 79


Inorder successor approach we choose 55 as the node to be replaced in place
of node 45

GRAPHS
A graph is an abstract data structure that is used to implement the mathematical concept of
graphs. It is basically a collection of vertices (also called nodes) and edges that connect these
vertices. A graph is often viewed as a generalization of the tree structure, where instead of
having a purely parent-to-child relationship between tree nodes, any kind of complex
relationship can exist.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

Graphs - Terminology and Representation

Definitions: Graph, Vertices, Edges


• Define a graph G = (V, E) by defining a pair of sets:
1. V = a set of vertices
2. E = a set of edges
Edges:
Each edge is defined by a pair of vertices o An edge connects the vertices that
define it

Vertices:

 Vertices also called nodes


 Denote vertices with labels

Representation:

 Represent vertices with circles, perhaps containing a label


 Represent edges with lines between circles
Example:
 V = {A,B,C,D}
 E = {(A,B),(A,C),(A,D),(B,D),(C,D)}

Examples of Graph applications:


 Cities with distances between
 Roads with distances between intersection points
 Course prerequisites
 Network and shortest routes
 Social networks
 Electric circuits, projects planning and many more...

Graph Classifications
here are several common kinds of graphs
 Weighted or unweighted
 Directed or undirected
 Cyclic or acyclic
 Multigraphs

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

Kinds of Graphs: Weighted and Unweighted :Graphs can be classified by whether or not
their edges have weights
Weighted graph:
 edges have a weight
 Weight typically shows cost of traversing
 Example: weights are distances between cities
Unweighted graph:
 edges have no weight Edges simply show connections
 Example: course prerequisites
Kinds of Graphs: Directed and Undirected
Graphs can be classified by whether or their edges are have direction
 Undirected Graphs: each edge can be traversed in either direction
 Directed Graphs: each edge can be traversed only in a specified direction

Undirected Graphs
 Undirected Graph: no implied direction on edge between nodes
The example from above is an undirected graph

fig 1

 In diagrams, edges have no direction (ie there are no arrows) o


Can traverse edges in either directions
 In an undirected graph, an edge is an unordered pair o
Actually, an edge is a set of 2 nodes, but for simplicity we
write it with parenthesis
 For example, we write (A, B) instead of {A, B}
 Thus, (A,B) = (B,A), etc
 If (A,B) E then (B,A) E

Directed Graphs
Digraph: A graph whose edges are directed (ie have a direction)

 Edge drawn as arrow


 Edge can only be traversed in direction of arrow
 Example: E = {(A,B), (A,C), (A,D), (B,C), (D,C)}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

fig 2

 In a digraph, an edge is an ordered pair


 Thus: (u,v) and (v,u) are not the same edge
 In the example, (D,C) ∈ E, (C,D) ∉ E
Degree of a Node
 The degree of a node is the number of edges incident on it.
 In the example above: (fig 1)
 Degree 2: B and C
 Degree 3: A and D
 A and D have odd degree, and B and C have even degree
 Can also define in-degree and out-degree
 In-degree: Number of edges pointing to a node
 Out-degree: Number of edges pointing from a node
Graphs: Terminology Involving Paths
 Path: sequence of vertices in which each pair of successive vertices is connected by an
edge
 Cycle: a path that starts and ends on the same vertex
 Simple path: a path that does not cross itself
That is, no vertex is repeated (except first and last)
 Simple paths cannot contain cycles
 Length of a path: Number of edges in the path
 Examples

Cyclic and Acyclic Graphs


 A Cyclic graph contains cycles Example: roads (normally)
 An acyclic graph contains no cycles Example: Course prerequisites
 Multigraph: A graph with self loops and parallel edges is called a
multigraph.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

Connected and Unconnected Graphs and Connected Components


• An undirected graph is connected if every pair of vertices has a path between it o
Otherwise it is unconnected

• A directed graph is strongly connected if every pair of vertices has a path between them,
in both directions Data Structures for Representing Graphs
• Two common data structures for representing graphs:
o Adjacency lists o
Adjacency matrix

Adjacency List Representation


An adjacency list is a way in which graphs can be represented in the computer’s
memory. This structure consists of a list of all nodes in G. Furthermore, every node is
in turn linked to its own list that contains the names of all other nodes that are adjacent
to it. The key advantages of using an adjacency list are:

• It is easy to follow and clearly shows the adjacent nodes of a particular node.
• It is often used for storing graphs that have a small-to-moderate number of edges. That
is, an adjacency list is preferred for representing sparse graphs in the computer’s
memory; otherwise, an adjacency matrix is a good choice.
• Adding new nodes in G is easy and straightforward when G is represented using an
adjacency list. Adding new nodes in an adjacency matrix is a difficult task, as the size
of the matrix needs to be changed and existing nodes may have to be reordered. Each
node has a list of adjacent nodes

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

Example (undirected graph): (fig 1)

A B C D

B A D
C A D

D A B C

Fig (1) adjacency lsit for the graph of fi g3

fig 3

E xample (directed graph):


 A: B, C,D
 B: D
 C: Nil
 D: C

Adjacency Matrix Representation


An adjacency matrix is used to represent which nodes are adjacent to one another. By definition,
two nodes are said to be adjacent if there is an edge connecting them. In a directed graph G, if
node v is adjacent to node u, then there is definitely an edge from u to v. That is, if v is adjacent
to u, we can get from u to v by traversing one edge. For any graph G having n nodes, the
adjacency matrix will have the dimension of n * n. In an adjacency matrix, the rows and columns
are labelled by graph vertices. An entry aij in the adjacency matrix will contain 1, if vertices vi
and vj are adjacent to each other. However, if the nodes are not adjacent, aij will be set to zero.
It. Since an adjacency matrix contains only 0s and 1s, it is called a bit matrix or a Boolean
matrix. The entries in the matrix depend on the ordering of the nodes in G. Therefore, a change
in the order of nodes will result in a different adjacency matrix.

Aij = 1 if there is an edge from Vi to Vj

0 otherwise

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

Adjacency Matrix: 2D array containing weights on edges


 Row for each vertex
 Column for each vertex
 Entries contain weight of edge from row vertex to column vertex
 Entries contain ∞ if no edge from row vertex to column vertex
 Entries contain 0 on diagonal (if self edges not allowed)
 Example undirected graph (assume self-edges not allowed):
ABCD
A0111
B 10∞1
C 1∞01
D1110

Example directed graph (assume self-edges allowed):

ABCD
A∞111
B ∞∞∞1
C ∞∞∞∞
D∞∞1∞

Disadv:Adjacency matrix representation is easy to represent and feasible as long as the graph is
small and connected. For a large graph ,whose matrix is sparse, adjacency matrix representation
wastes a lot of memory. Hence list representation is preferred over matrix representation.

Graph traversal algorithms


Traversing a graph, is the method of examining the nodes and edges of the graph. There are
two standard methods of graph traversal. These two methods are:
1. Breadth-first search
2. Depth-first search

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

While breadth-first search uses a queue as an auxiliary data structure to store nodes for further
processing, the depth-first search scheme uses a stack.
Breadth-first search algorithm
Breadth-first search (BFS) is a graph search algorithm that begins at the root node and explores
all the neighbouring nodes. Then for each of those nearest nodes, the algorithm explores their
unexplored neighbour nodes, and so on, until it finds the goal. That is, we start examining the
node A and then all the neighbours of A are examined. In the next step, we examine the
neighbours of neighbours of A, so on and so forth. This means that we need to track the
neighbours of the node and guarantee that every node in the graph is processed and no node is
processed more than once. This is accomplished by using a queue that will hold the nodes that
are waiting for further processing.
Algorithm for BFS traversal
• Step 1: Define a Queue of size total number of vertices in the graph.
• Step 2: Select any vertex as starting point for traversal. Visit that vertex and insert it
into the Queue.
• Step 3: Visit all the adjacent vertices of the verex which is at front of the Queue which
is not visited and insert them into the Queue.
• Step 4: When there is no new vertex to be visit from the vertex at front of the Queue
then delete that vertex from the Queue.
• Step 5: Repeat step 3 and 4 until queue becomes empty.
• Step 6: When queue becomes Empty, then the enqueue or dequeue order gives the BFS
traversal order.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

Depth-first Search Algorithm


Depth-first search begins at a starting node A which becomes the current node. Then, it
examines each node N along a path P which begins at A. That is, we process a neighbour of A,
then a neighbour of neighbour of A, and so on.
During the execution of the algorithm, if we reach a path that has a node N that has already
been processed, then we backtrack to the current node. Otherwise, the unvisited (unprocessed)
node becomes the current node. The algorithm proceeds like this until we reach a dead-end (end
of path P). On reaching the deadend, we backtrack to find another path P. The algorithm
terminates when backtracking leads back to the starting node A.
In this algorithm, edges that lead to a new vertex are called discovery edges and edges that lead
to an already visited vertex are called back edges. Observe that this algorithm is similar to the
in-order traversal of a binary tree. Its implementation is similar to that of the breadthfirst search
algorithm but here we use a stack instead of a queue.
We use the following steps to implement DFS traversal...
 Step 1: Define a Stack of size total number of vertices in the graph.
 Step 2: Select any vertex as starting point for traversal. Visit that vertex and push it
on to the Stack.
 Step 3: Visit any one of the adjacent vertex of the verex which is at top of the stack
which is not visited and push it on to the stack.
 Step 4: Repeat step 3 until there are no new vertex to be visit from the vertex on top
of the stack.
 Step 5: When there is no new vertex to be visit then use back tracking and pop one
vertex from the stack.
 Step 6: Repeat steps 3, 4 and 5 until stack becomes Empty.
 Step 7: When stack becomes Empty, then produce final spanning tree by removing
unused edges from the graph

PTO

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN
DATASTRUCTURES AND APPLICATIONS BCS304

Applications OF graphs
 Graphs are constructed for various types of applications such as:
 In circuit networks where points of connection are drawn as vertices and component
wires become the edges of the graph.
 In transport networks where stations are drawn as vertices and routes become the edges
of the graph.
 In maps that draw cities/states/regions as vertices and adjacency relations as edges.
 In program flow analysis where procedures or modules are treated as vertices and calls
to these procedures are drawn as edges of the graph.
 Once we have a graph of a particular concept, they can be easily used for finding shortest
paths, project planning, etc.
 In flowcharts or control-flow graphs, the statements and conditions in a program are
represented as nodes and the flow of control is represented by the edges.
 In state transition diagrams, the nodes are used to represent states and the edges represent
legal moves from one state to the other.
 Graphs are also used to draw activity network diagrams. These diagrams are extensively
used as a project management tool to represent the interdependent relationships between
groups, steps, and tasks that have a significant impact on the project.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING(AIML) RIT


HASSAN

You might also like