dsa mod 4
dsa mod 4
3) The keys (if any) in the right subtree are larger than the key in the root.
4) The left and right subtrees are also binary search trees.
5) The root has a key.
Example:
Recursive search of a binary search tree: Return a pointer to the element whose key is k, if there
is no such element, return NULL. We assume that the data field of the element is of type elemenet
and it has two components key and item.
rootnode * search(rootnode * root, int k)
{
if
(root==NULL)
return NULL;
if (k ==root→data.key)
return (tree);
if (k <root→data.key)
Prepared by: Sowmya H D/Asst Prof, CSE Dept SSCE, Anekal
return(root);
if (k <root→data.key)
root = root→leftChild;
else
root = root→rightChild;
}
return NULL;
}
Inserting in to a Binary Search Tree: Binary search tree has distinct values, first we search the tree for
the key and if the search is unsuccessful the key is inserted at the point the search terminated
ptr→data.key = k;
ptr→data.item = Item;
ptr→leftChild = ptr→rightChild = NULL;
if (root==NULL)
{
root=ptr;
return(root);
}
if(lastnode!=NULL)
{
if (k < lastnode→data.key)
lastnode→leftChild = ptr;
else
lastnode→rightChild =
ptr;return (root);
}
}
If the element is present or if the tree is empty the function Modifiedsearch returns NULL. If the
element is not present it return a pointer to the last node searched.
Modifiedsearch(Treenode *root,int k)
{
TreeNode *temp,*prev;
temp==node;
prev=NULL;
If(temp==NULL)
return(NULL);
while(temp!=NULL)
{ if(temp->data.key==k)
{ printf(“element already found”);
return(NULL);
}
if(key<temp->data.key)
{
prev=temp;
temp=temp->lchild;
} else
{
Prev=temp;
Temp=temp->rchild;
}
} retrun(prev);
Case 1: N has no children. Then N is deleted from T by replacing the location of the node N in the
parent(N) by the NULL pointer
Deleting node
Case 2: If N has exactly one child. Then N is deleted from T by replacing the location of N in Parent
(N) by the location of the only child of N.
Example: Deleting Node 75 with exactly one children
Case 3: N has Two children. Let S(N) denote the inorder successor of N(S(N) does not have a left
child).Then N is deleted from T by first deleting S(N) from T (by using case1 or cae 2) and then
replacing node N in T by the node S(N).
{
temp = node-
>lchild; free(node);
return temp;
}
// node with two
childrenelse
{
temp = node->rchild;
Prepared by: Sowmya H D/Asst Prof, CSE Dept SSCE, Anekal
while(temp-
>lchild!=NULL)
//Get the inorder successor
temp=temp->lchild;
node->data.item = temp-
>data.item;node-
>data.key=temp->data.key;
node->rlink = delete_element(node->rchild, temp->data.key); return node;
}
}
}
There are some properties of Tournament trees. These are like below −
This tree is rooted. So the link in the tree and directed path from parent to children, and there
is a unique element with no parents
The parent value is less or equal to that node to general any comparison operators, can be used as
long as the relative value of the parent and children are invariant throughout the tree
Trees with a number of nodes not a power of 2, contain holes. Holes can be present at any place
in the tree.
This tree is a proper generalization of binary heaps
The root will represent overall winner of the tournament.
Winner Tree
Looser Tree
Winner Tree
Winner tree is a complete binary tree, in which each node is representing the smaller or greater of its two
children, is called winner tree. The root is holding the smallest or greatest node of the tree. The winner of
the tournament tree is the smallest or greatest n key in all the sequences. It is easy to see that winner tree
can be formed in O(log n) time.
Looser 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. But in this overall winner is stored at tree[0].
The looser is an alternative representation, that stores the looser of a match at the corresponding node. An
advantage of the looser is that, to restructure the tree after winner tree been output, it is sufficient to examine
node on the path from leaf to root rather than the sibling of the nodes on this path.
Same as min winner and max winner, min looser and max looser trees also available.
Suppose there are some keys, 10, 2, 7, 6, 5, 9, 12, 1. So we will create minimum winner tree at first.
Forests
A forest is a disjoint set of trees. In other words, it's a collection of trees where there are no cycles present.
Each tree in a forest consists of nodes connected by edges, similar to a real-life tree structure with branches
and leaves.
Forest
Binary Tree
Forest Traversals
Forest preorder
1. If F is empty then return
2. Visit the root of the first tree of Forest
3. Traverse the subtrees of the first tree of forest in preorder
4. Traverse the remaining trees of Forest in preorder
Forest Inorder
1. If F is empty then return
2. Traverse the subtrees of the first tree of forest in Inorder
3. Visit the root of the first tree
4. Traverse the remaining trees of Forest in Inorder
Forest Postorder
1. If F is empty then return
2. Traverse the subtrees of the first tree of forest in postorder
3. Traverse the remaining trees of Forest in Postorder
4. Visit the root of the first tree
The disjoint set data structure is also known as union-find data structure and merge-find set. It is a data
structure that contains a collection of disjoint or non-overlapping sets. The disjoint set means that when
the set is partitioned into the disjoint subsets. The various operations can be performed on the disjoint
subsets. In this case, we can add new sets, we can merge the sets, and we can also find the representative
member of a set. It also allows to find out whether the two elements are in the same set or not efficiently.
The disjoint set can be defined as the subsets where there is no common element between the two sets.
Let's understand the disjoint sets through an example.
s1 = {1, 2, 3, 4}
Prepared by: Sowmya H D/Asst Prof, CSE Dept SSCE, Anekal
s2 = {5, 6, 7, 8}
We have two subsets named s1 and s2. The s1 subset contains the elements 1, 2, 3, 4, while s2 contains
the elements 5, 6, 7, 8. Since there is no common element between these two sets, we will not get anything
if we consider the intersection between these two sets. This is also known as a disjoint set where no elements
are common. Now the question arises how we can perform the operations on them. We can perform only
two operations, i.e., find and union.
In the case of find operation, we have to check that the element is present in which set. There are two sets
named s1 and s2 shown below:
Suppose we want to perform the union operation on these two sets. First, we have to check whether the
elements on which we are performing the union operation belong to different or same sets. If they belong
to the different sets, then we can perform the union operation; otherwise, not. For example, we want to
perform the union operation between 4 and 8. Since 4 and 8 belong to different sets, so we apply the union
operation. Once the union operation is performed, the edge will be added between the 4 and 8 shown as
below:
When the union operation is applied, the set would be represented as:
s1Us2 = {1, 2, 3, 4, 5, 6, 7, 8}
For example, if we have 10 elements numbered 0 through 9, we may partition them into three dis- joint sets,
S1 = {0, 6, 7, 8}, S2 {1, 4, 9}, and S3 {2, 3, 5).
The minimal operations that we wish to perform on these sets are:
(1) Disjoint set union. If S i and Sj are two disjoint sets, then their union Si U Sj = {all elements, x, such
that x is in Si or Sj}. 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.
Two or more sets have no element in common are called disjoint sets. Disjoint set data structure is also
referred to as union find data structure because of its union and find operations.
Disjoint Sets:
Disjoint Sets is one of the most powerful and yet simple data structure. The idea of Disjoint Sets can be
perfectly applied in finding the minimal spanning tree.
The Disjoint Sets consist of two basic operations: finding the group (parent) of any element, unioning two or
more sets.
Considering above forests (a set of trees), each tree represents a set. We use an one-dimension array to store
the fathers of every node. We can initialize them by -1 or itself, meaning they belong to their own group at
the beginning. Otherwise, the value represents its father node.
Finding the root-parent of any group can be implemented by two styles: recursive or iterative. The recursive
method is short and straightforward.
Prepared by: Sowmya H D/Asst Prof, CSE Dept SSCE, Anekal
1 def find(x):
2 global father
3 if x != father[x]:
4 father[x] = find(x) // compress the paths
5 return father[x]
Graphs
Definitions
Example:
Undirected Graph: In an undirected graph the pair of vertices representing an edge is unordered.
Example:
V(G)={a,b,c,d}
E(G)={(a,b),(a,d),(b,d),(b,c)
thus the pairs (u,v) and (v,u) represent the same edge.
Directed Graph (digraph): In a directed graph each edge is represented by a directed pair (u,v), v is
the head and u is the tail of the edge. Therefore (v,u) and(u,v) represent two different edges.
Example:
V(G)={a,b,d}
Self Edges/Self Loops: Edges of the form(v,v) are called self edges or self loops . It is an edge
Prepared by: Sowmya H D/Asst Prof, CSE Dept SSCE, Anekal
Mutigraph: A graph with multiple occurrences of the same edge is called a multigraph
Example:
Complete Graph: An undirected graph with n vertices and exactly n(n-1)/2 edges is said to be a
complete graph. In a graph all pairs of vertices are connected by an edge.
Example : A complete graph with n=3 vertices
Adjacent Vertex
If (u,v) is an edge in E(G), then we say that the vertices u and v are adjacent and the edge(u,v) is
incident on vertices u and v.
Path: A path from vertex u to v in graph g is a sequence of vertices u, i1,i2,…….ik, v such that
(u,i1),(i1,i2)………(ik,v) are edges in E(G). if G‘ is directed then the path consists of
<u,i1>,<i1,i2>………<ik,v> edges in E(G‘).
Cycle: A cycle is a simple path in which all the vertices except the first and last vertices are distinct.
The first and the last vertices are same.
Example :
(B,C),(C,D)(D,E)(E,A)(A,B) is a cycle
Degree of a vertex : In a undirected graph degree of a vertex is the number of edges incident on a
vertex.
In a directed graph the in-degree if a vertex v is the number of edges for which v is the head i.e. the
number of edges that are coming into a vertex. The out degree is defined as the number of edges for
which v is the tail i.e. the number of edges that are going out of a vertex
Subgraph: A subgraph of G is a graph G‘ such that V(G‘) is a subset of V(G) and E(G‘) is a subset of
E(G)
Example :
Graph(G) Subgraph(G‘)
Connected Graph: An undirected graph G is said to be connected if for every pair of distinct vertices
u and v in V(G) there is a path from u to v in G.
Strongly connected graph : A directed graph G is said to be strongly connected if for every pair of
distinct vertices u an v in V(G), there is a directed path from u to v and from v to u.
ADT Graph
Objects: a nonempty set of vertices and a set of undirected edges, where each edge is a pair of vertices.
Graph Representation
• Adjacency Matrix
• Adjacency List
• Adjacency Multilist
Adjacency Matrix: Let G=(V,E) be a graph with n vertices, n>=1. The adjacency matrix of G is a
two dimensional n*n array for example a, with the property that a[i][j]=1 if there exist ane edge (i,j)
(for a directed graph edge <i,j> is in E(G).a[i][j]=0 if no such edge in G.
Example: Graph G1
0
Adjacency Matrix
0 1 2 3
0 0 1 1 1
1 2
1 1 0 1 1
2 1 1 0 1
3 1 1 1 0
Adjacency list: In adjacency matrix the n rows of the adjacency matrix are represented as n chains.
There is one chain for each vertex in G. The nodes in chain i represent the vertices that are adjacent
from vertex i. The data field of a chain node stores the index of an adjacent vertex.
• For an undirected graph with n vertices and e edges. The linked adjacency lists representation
requires an array of size n and 2e chain nodes.
• The degree of any vertex in an undirected graph may be determined by counting the number
of nodes in the adjacency list. For a digraph the number of list nodes is only e.
Adjacency Multi lists: For each edge there will be exactly one node, but this node will be in two
list(i.e., the adjacency list for each of the two nodes to which it is incident). A new field is necessary
to determine if the edge is determined and mark it as examined.
Where m is a Boolean mark field that may be used to indicate whether or not the edge has been
examined.
Example: The adjacency multilist for graph G1 is shown below
weights may represent the distance from one vertex to another or the cost for going from one vertex
to an adjacent vertex. The adjacency matrix and list maintains the weight information also. A graph
with weighted edges are also called network.
Example:
Given an undirected graph G=(V,E) and a vertex v in V(G) ,there are two ways to find all the vertices
that are reachable from v or are connected to v .
A global array visited is maintained , it is initialized to false, when we visit a vertex i we change the
visited[i] to true.
Global Declaraions
}
Prepared by: Sowmya H D/Asst Prof, CSE Dept SSCE, Anekal
Example: For the graph given below if the search is initiated from vertex 0 then the vertices are
visited in the order vertex 3, 1, 2
1 2
[0] 1 2 0
3
[1] 0 3 0
2
[2] 0 3 0
1
[3] 1 2 0
0
struct node
{ int vertex;
struct node * link;
};
typedef struct node queue;
queue * front,*rear;:
int visied[max_vertics];
void addq(int);
int delete();
void bfs(int v)
int i, cur;
visited[v] = 1;
q[++rear] = v;
while(front!=rear)
cur = q[++front];
for(i=0;i<n;i++)
if((a[cur][i]==1)&&(visited[i]==0))
q[++rear] = i;
visited[i] = 1;
Connected components
In an undirected graph refers to a group of vertices that are connected to each other through edges, but
not connected to other vertices outside the group.
For example in the graph shown below, {0, 1, 2} form a connected component and {3, 4} form another
connected component.
A connected component is a set of vertices in a graph that are connected to each other.
A graph can have multiple connected components.
Inside a component, each vertex is reachable from every other vertex in that component.
There are several algorithms to identify Connected Components in a graph. The most popular ones are:
Depth-First Search (DFS)
Breadth-First Search (BFS)
Union-Find Algorithm (also known as Disjoint Set Union)
Graph Theory: It is used to find subgraphs or clusters of nodes that are connected to each
other.
Computer Networks: It is used to discover clusters of nodes or devices that are linked and
have similar qualities, such as bandwidth.
Image Processing: Connected components also have usage in image processing.
void connected(void)
{
int i;
for (i=0;i<n;i++)
if(!visited[i])
{
dfs(i);
printf(“\n”);
}
}
Spanning Trees:
A spanning tree is a subset of Graph G, such that all the vertices are connected using minimum possible
number of edges. Hence, a spanning tree does not have cycles and a graph may have more than one
spanning tree.
A minimum spanning tree (MST) is defined as a spanning tree that has the minimum weight among
all the possible spanning trees.
1. It is connected, i.e. it is possible to reach every vertex from every other vertex, by a simple path.
2. Even after removing any vertex the graph remains connected.
The given graph is clearly connected. Now try removing the vertices one by one and observe. Removing
any of the vertices does not increase the number of connected components. So the given graph is
Biconnected.
Now consider the following graph which is a slight modification in the previous graph.
Prepared by: Sowmya H D/Asst Prof, CSE Dept SSCE, Anekal
In the above graph if the vertex 2 is removed, then here's how it will look:
Clearly the number of connected components have increased. Similarly, if vertex 3 is removed there will
be no path left to reach vertex 0 from any of the vertices 1, 2, 4 or 5. And same goes for vertex 4 and 1.
Removing vertex 4 will disconnect 1 from all other vertices 0, 2, 3 and 4. So the graph is not Biconnected.