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

DSA Module 4

The document covers advanced data structures including binary search trees, selection trees, forests, and graphs, detailing their properties, operations, and traversal methods. It explains how binary search trees optimize insertion, deletion, and search operations, while selection trees are used for tournament structures. Additionally, it introduces graph concepts, including types, representations, and traversal algorithms like BFS and DFS.

Uploaded by

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

DSA Module 4

The document covers advanced data structures including binary search trees, selection trees, forests, and graphs, detailing their properties, operations, and traversal methods. It explains how binary search trees optimize insertion, deletion, and search operations, while selection trees are used for tournament structures. Additionally, it introduces graph concepts, including types, representations, and traversal algorithms like BFS and DFS.

Uploaded by

lxl.reshma.lxl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Module 4

• TREES(Cont..): Binary Search trees, Selection Trees, Forests,


Representation of Disjoint sets, Counting Binary Trees,
• GRAPHS: The Graph Abstract Data Types, Elementary Graph
Operations
• A binary search tree has a better performance than any of the data
structures studied so far when the operations we wish to perform are
insertion, deletion, and searching
• A binary search tree is a binary tree.
• It may be empty.
• If it is not empty, it satisfies the following properties:
• Every element has a key, and no two elements have the same key,
that is, the keys are unique.
• The keys in a nonempty left subtree must be smaller than the key in
the root of the subtree.
• The keys in a nonempty right subtree must be larger than the key in
the root of the subtree.
• The left and right subtrees are also binary search trees
BST-Searching A Binary Search Tree
• To search for an element with a key.
• First begin at the root.
• If the root is NULL, the search tree contains no elements and the search is
unsuccessful.
• Otherwise, compare key with the key value in root.
• If key equals root's key value, then the search terminates successfully.
• If key is less than roots key value, then no element in the right subtree can
have a key value equal to key. Therefore, search the left subtree of root.
• If key is larger than roots key value, we search the right subtree of root.
Recursive search
NODE* Search(NODE *node, int data){
if(node == NULL)
printf("\nElement not found");
else if(data < node->data)
node->left=Search(node->left, data);
else if(data > node->data)
node->right=Search(node->right, data);
else
printf("\n Element found: %d", node->data);
return node;
}
Iterative search
NODE* Search(NODE *node, int data){
while(node){
if(node->data==data) {
printf("\n Element found: %d", node->data);
return node;
}
else if(data < node->data)
node=node->left;
else if(data > node->data)
node=node->right;
}
printf("\n Element found: %d", node->data);
return NULL;
}
Insertion into BST
NODE* Createtree(NODE *node, int data){
if (node == NULL) {
NODE *temp= (NODE*)malloc(sizeof(NODE));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
if (data < (node->data))
node->left = Createtree(node->left, data);
else if (data > node->data)
node -> right = Createtree(node->right, data);
else
printf(“duplicate data found”);
return node;
}
BST Traversals void Postorder(NODE *node){
void Inorder(NODE *node){ void Preorder(NODE *node){ if(node != NULL) {
if(node != NULL){ if(node != NULL) { Postorder(node->left);
Inorder(node->left); printf("%d\t", node->data); Postorder(node->right);
Preorder(node->left); printf("%d\t", node->data);
printf("%d\t", node->data);
Preorder(node->right); }
Inorder(node->right); } }
} }
}
SELECTION TREES
• A tournament tree is a form of complete binary tree in which each node denotes
a player.
• The last level has n-1 nodes (external nodes) used to represent all the players,
and the rest of the nodes (internal nodes) represent either the winner or loser
among them.
• It is also referred to as a Selection tree.
• There are two kinds of selection trees: winner trees and loser trees.
• A winner tree is a complete binary tree in which each node represents the
smaller of its two children. Thus, the root node represents the smallest node in
the tree.
• Looser Trees are complete binary tree for n players where n external nodes and n
– 1 internal nodes are present.
• The looser of the match is stored in the internal nodes.
Forest
• A forest is a set of n>= 0disjoint trees
• The concept of a forest is very close to that of a tree because if we
remove the root of a tree we obtain a forest.
• For example, removing the root of any binary tree produces a forest
of two trees.
Transforming A forest Into A Binary Tree
• Definition: If T1,T2, ..Tn, is a forest of trees, then the binary tree
corresponding to this forest, denoted by B(T1,, ..-, Tn):
Representation of Disjoint sets
• Assume that the elements of the sets are the numbers 0, 1, 2, •••,n-1.
• Sets being represented are pairwise disjoint, that is, if Si and Sj are two sets and
i<> j, then there is no element that is in both Si, and Sj.
• For example, if we have 10 elements numbered 0 through 9, we may partition
them into three disjoint sets, S1 = {0, 6, 7, 8), S2 = {1, 4, 9}, and S3 = {2, 3, 5}.
Operations on set

• (1) Disjoint set union. If Si and Sj are two disjoint sets, then their union Si U
Sj = {all elements, x, such that x is in S1 or S2). Thus, S1 U S2 = {0, 6, 7, 8, 1, 4,
9}. Since we have assumed that all sets are disjoint, following the union of Si
and Sj we can assume that the sets Si and Sj no longer exist independently.
That is, we replace them by Si U Sj.
• (2) Find(i). Find the set containing the element, i. For example, 3 is in set S3
and 8 is in set S1.
Union And Find Operations
Data representation of S1, S2, and S3

Array representation of set


Union and Find
union(Q, 1) union(2, 3) union(4, 5) union(6, 7) union(0, 2) union(4, 6) union(0, 4)
Leftist tree
shortest (x)

Definition: A leftist tree is a binary tree such that if it is not empty, then
shortest {left - child (x)) > shortest {right - child (x)) for every internal node x.
Node structure
Combining two leftist trees
• leave the left subtree of a unchanged and combine the right subtree
of a and the entire binary tree b
• The resulting binary tree will become the new right subtree of a.
• When combining the right subtree of a and the binary tree b, we
notice that 5 < 50. So, 5 should be in the root of the combined tree.
• combine the subtrees with root 8 and 50. Since 8 < 50 and 8 has no
right subtree, we can make the subtree with root 50 the right subtree
of 8.
• Simply interchanging the left and right subtrees at these nodes results
leftist tree
leave the left subtree of a unchanged and combine the right subtree of a and the entire binary tree b
The resulting binary tree will become the new right subtree of a.
Simply interchanging the left and right subtrees at these nodes results leftist tree
GRAPHS
• The Graph Abstract Data Types, Elementary Graph Operations
• The first recorded evidence of the use of graphs dates
back to 1736 when Leonhard Euler used them to solve
the classic Koningsberga bridge problem.
• In Koningsberga, the Pregal river flows around the
island of Kneiphof.
• There are four land areas, labeled A through D that
have this river on their border.
• Seven bridges, labeled a through g, connect the land
areas.
• The Koenigsberg bridge problem is as follows: Starting
at some land area, is it possible to return to our
starting location after walking across each of the
bridges exactly once
Classic Koningsberga bridge problem.
starts at node C then continues to node B, then A, then D, back
to B, then C, before ending at node D
The path begins at node C before going to B then back to C, then to
node D, then A, before node B, then back to A, then D, before ending
at node B
start from land area B
walk across bridge a to island A
take bridge e to area D
take bridge g to C
take bridge d to A
take bridge b to B
take bridge f to D

Euler solved the problem by using a graph (actually a multigraph) in which the land areas are vertices
and the bridges are edges. His solution is not only elegant, it applies to all graphs
This traverse is known as Eulerian walk
• A graph, G, consists of two sets: a finite, nonempty set of vertices,
and a finite, possibly empty set of edges.
• V(G) and E(G) represent the sets of vertices and edges of G,
respectively.
• Alternately, we can write G = (V, E) to represent a graph.
• An undirected graph is one in which the pair of vertices representing
any edge is unordered.
• For example, the pairs (v0,v1) and (v1, v0) represent the same edge.
• A directed graph is one in which we represent each edge as a directed
pair of vertices.
• For example, the pair <vo, v1> represents an edge in which is the tail
and vj is the head. Therefore, <vo, v1> and <V1, v0> represent two
different edges in a directed graph
• A complete graph is a graph that has the maximum number of edges. For an
undirected graph with n vertices, the maximum number of edges is the
number of distinct, unordered pairs, (v,, vy), i j. This number is: n(n - l)/2.
• For a directed graph on n vertices, the maximum number of edges is: n(n - 1)

Number of edges:
Number of edges:
4*3/2=6
4*3=12
Graph G2 is a tree, while graphs G1 and G3 are not.
• If (v0,v1) is an edge in an undirected graph, then the vertices v1 and
v2 are adjacent and the edge (v1,v2) is incident on vertices V1 and v2.
• For example, in graph G2, vertices 3, 4, and 0 are adjacent to vertex 1;
and edges (0, 2), (2, 5), and (2, 6) are incident on vertex 2.
• If <V0, v1> is a directed edge, then vertex v0 is adjacent to vertex V1,
while V1 is adjacent from v0.
• The edge <vo, V1> is incident on v0 and V1
• In G3, the edges incident to vertex 1 are <0, 1>, <1, 0>, and <1, 2>
Subgraph
• A graph may not have an edge from a vertex, i, back to itself. That is,
the edge, (v,, V,) or <Vj, V/> is not legal. Such edges are known as self
loops
• A graph may not have multiple occurrences of the same edge. If we
remove this restriction, we obtain a data object referred to as a
multigraph
• A path from vertex Vp to vertex vq in a graph, G, is a sequence of vertices
vp,vi1,vi2…..vin, vq such that (vp,vi1), (vi1,vi2),….(vin,vq) are edges in an
undirected graph.
• If G’ is a directed graph, then the path consist of <vp,vi1>,<vi1,vi2>,…<Vin,vq>.
The length of a path is the number edges on it
• A connected component, or simply a component, of an
undirected graph is a maximal connected subgraph. For
example, G4 has two components, H1 and H2. A tree is a
graph that is connected and acyclic (it has no cycles).
• A directed graph is strongly connected if, for every pair of
vertices Vi, Vj in V(G), there is a directed path from Vj to vi
and also from vj to vi.
• Graph G3 is not strongly connected since there is no path
from vertex 2 to vertex 1
• The degree of a vertex is the number of edges incident to that
vertex. For example, the degree of vertex 0 in G3 is 2.
• For a directed graph, we define the in-degree of a vertex v as
the number of edges that have v as the head, and the out-
degree as the number of edges that have v as the tail.
• For example, vertex 1 of G3 has in-degree 1, out-degree 2, and
degree 3.
• If di is the degree of a vertex i in a graph G with n vertices and e
edges, then the number of edges is:
Graph ADT
Graph Representations-Adjacency Matrix

• Let G = (V, E) be a graph with n vertices, n >= 1. The adjacency matrix


of G is a two- dimensional n x n array, say adj-mat.
• If the edge (Vj, Vj) (<Vi, Vj> for a digraph) is in E(G), adj-mat[i][j] = 1.
If there is no such edge in E(G), adj-mat[i][j] = 0
• Degree of a vertex
Adjacency Lists
Adjacency list for G1
Adjacency list for G4
Adjacency list for G3
Alternate representation
Adjacency multi list
Elementary Graph Operations
BFS
• Step 1: SET STATUS = 1 (ready state) for each node in G
• Step 2: Enqueue the starting node A and set its STATUS = 2 (waiting
state)
• Step 3: Repeat Steps 4 and 5 until QUEUE is empty
• Step 4: Dequeue a node N. Process it and set its STATUS = 3
(processed state).
• Step 5: Enqueue all the neighbours of N that are in the ready state
(whose STATUS = 1) and set their STATUS = 2 (waiting state)
• [END OF LOOP]
• Step 6: EXIT
Step 1 2 3 4 5 6 7 8
Q1 Status 2 A BD D,C F CF FEG EG G -
Q2 Status 3 - A AB ABD ABDC ABDC F ABDC FE ABDC FEG
DFS
• Step 1: SET STATUS = 1 (ready state) for each node in G
• Step 2: Push the starting node A on the stack and set its STATUS = 2
(waiting state)
• Step 3: Repeat Steps 4 and 5 until STACK is empty
• Step 4: Pop the top node N. Process it and set its STATUS = 3
(processed state)
• Step 5: Push on the stack all the neighbors of N that are in the ready
state (whose STATUS = 1) and set their STATUS = 2 (waiting state)
• [END OF LOOP]
• Step 6: EXIT
Stack Stack Stack Stack Stack Stack Stack Stack Stack
H A B B B C E E
D F G

- A H D F B C G E
• #include<stdlib.h>
• #include<stdio.h>
• int adj[20][20],visited[20], G[20], front = -1,rear =-1, top = -1,n,i;
void BFS(int v) { //uses G as Queue
int cur;
visited[v] = 1; // start from any vertex -as starting vertex
G[++rear] = v; // insert into queue
while(front!=rear){ //if queue is not empty
cur = G[++front]; // remove vertex from queue and start explore from this vertex
for(i=1;i<=n;i++){
if((adj[cur][i]==1)&&(visited[i]==0)){ // if there is a neighbours
G[++rear]=i; //insert the vertex to queue
visited[i]=1; // mark it as visited
printf("%d%d \n",cur,i); // add it to result
}
}
}
}
void DFS(int v) { //uses G as Stack
int i;
top=-1;
visited[v]=1;
printf("%d ",v);
do{
i=1;
while(i<=n){
if(adj[v][i] == 1 && visited[i] == 0 ){
G[++top]=v; //suspend the vertex for later exploration
visited[i]=1; //mark it as visited
printf("%d ",i); //add this to result
v=i; //start from this vertext
i=1;
}
else
i++;
}
v=G[top--];
}while(top!=-1);
}
int main(){
int ch, start, i, j;
printf("\nEnter the number of vertices in graph: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix:\n");
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
scanf("%d", &adj[i][j]);
do{
printf("\n1. BFS\n2. DFS \n3. Exit");
printf("\n Enter your choice: ");
scanf("%d", &ch);
for(i=1;i<=n;i++)
visited[i] = 0;
printf("\n Enter the starting vertex: ");
scanf("%d", &start);
printf("\nNodes reachable from starting vertex %d are:", start);
switch(ch){
case 1: BFS(start); break;
case 2: DFS(start); break;
case 3: exit(0);
}
}while(ch!=3);
}

You might also like