Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

MODULE-4

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 93

MODULE -4

BINARY SEARCH TREES


DICTIONARY
• Is a collection of pairs, each pair has a key and an associated item.
• no two pairs have the same key
BINARY SEARCH TREE
A binary search tree is a binary tree. It may be empty. If it is not empty,
it satisfies the following properties:
1. Each node has exactly one key and the keys in the tree are distinct
2. The keys(if any) in the left subtree are smaller than the key in the
root
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
Searching A Binary Search Tree
• Let an element k is to search in binary search tree. Start search from
root node of the search tree.
1.If root is NULL, search tree contains no nodes and search
unsuccessful.
2. Otherwise, compare k with the key in the root. If k equals the root’s
key, terminate search
3 if k is less than key value, search element k in left subtree otherwise
search element k in right subtree.
The function search recursively searches the subtrees.
Structure definition for a node

struct node {
int key;
struct node *left,
*right;
};
struct node* search(struct node* root, int
key)
{

if (root == NULL ) return NULL;


if ( root->key == key)
return root;
if (root->key < key)
return search(root->right, key);

return search(root->left, key);


}
Iterative Search
struct node* iterSearch(struct node* root, int key)
{
while (root!=NULL)
{
if (key == root->data) return root;
if (key <root->data)
root= root->left_child;
else
root= root->right_child;
}
return NULL;
}
Inserting Into A Binary Search
Tree
• To insert a new element, key, we must first verify that the key is
different from those of existing elements
• A new key is always inserted at the leaf by maintaining
the property of the binary search tree.
Step 1: create a new node using malloc() and store key value in the new
node.
Step 2:if tree is empty ,then new node will be the first node in the tree
Step 3:if tree is not empty, to insert a new element, key, we must first
verify that the key is different from those of existing elements.
Step 4: if the key in the new node is unique, insert it at appropriate
position in BST
Structure definition for a node
in a tree
struct node
{
int key;
struct node * llink,*rlink;
};
typedef struct node* NODE;
NODE insert(NODE root, int item)
{
NODE temp,cur,prev;
temp=(NODE *) malloc(sizeof(NODE));
tempkey=item;
templlink=temprlink=NULL;

If( root==NULL) return temp;


prev= NULL;
Cur=root;
while (cur!=NULL)
{
prev=cur;
if (curkey==item)
{
printf( “duplication is not allowed”);
free( temp);
return root;
}
if(item<curkey)
cur=curllink;
else
cur=currlink;
}
if (item<prevkey)
prevllink=temp;
else
prevrlink=temp;
return root;
}
Deletion in Binary Search Tree
(BST)
While deleting a node from a tree, the memory is to be released.
Deletion operation is the complex operation in the binary search tree.
To delete a node from the tree consider the following three possibilities.

Case 1: Node to be deleted is a leaf node

Case 2: Node with one child.

Case 3: Node with two children.


Case 1: Deleting the leaf node
1. Search the parent of the leaf
node.
2. Make the parent link of the leaf
node as NULL.
3.Release Memory.
Case 2: Deleting the node with
only one child
1.Search the parent of the node to be
deleted.
2.Assign the parent link to the child node
of the node to be deleted.
3.Release the memory of the deleted
node. If a node has one child, it can be
deleted by adjusting its parent pointer to
point to its child node
Case 3:Deleting a node with two
children.
The general strategy is to replace the data of the node to
be deleted with its smallest data of the right sub tree (or)
largest data of the left sub tree and recursively delete the
data or node.
SELECTION(tournament )TREES
• A tournament tree is a complete binary tree that is most efficiently
stored by using the array-based binary tree
• Each sequence consists of some number of records and is in
nondecreasing order of a designated field called the key.
• An ordered sequence is called a run. Let n be the number of records
in the k runs together.
Types in selection trees
• two varieties of tournament trees
1. Winner tree
2. Loser tree
Winner tree

• Is a complete binary tree in which each node represents the


smaller/larger of its two children.
• The root node represents the winner
• In a tournament tree (also called a selection tree), each external node
represents a player and each internal node represents the winner of
the match played between the players represented by its children
nodes
Winner trees are of
1. Max winner tree
2. Min winner tree
Min winner tree
• The construction of this selection tree may be compared to the
playing of a tournament in which the winner is the record with the
smaller key. Then, each nonleaf node in the tree represents the
winner of a tournament and the root node represents the overall
winner or the smallest key.
Loser Trees
• A selection tree in which each non leaf node retains a pointer to the
loser is called a tree of losers.
FORESTS
Definition: A forest is a set of n> 0 disjoint trees
Transforming A Forest Into A
Binary Tree
• To transform this forest into a single binary tree, we first obtain the
binary tree representation for each of the trees in the forest.
• We then link all the binary trees together through the sibling field of
the root node.
• Definition: If T1,T2,…..,Tn is a forest of trees, then the binary tree
corresponding to this forest, denoted by B(T1,T2,…..,Tn ):
1.is empty, if n = 0
2. has root equal to root (T1); has left subtree equal to B(T11,T12,
…..,T1m) , T11,T12,…..,T1m are the subtrees of root (T1); and has right
subtree B(T2,……..,Tn )
Forest Traversals
• Preorder, inorder, and postorder traversals of the corresponding
binary tree T of a forest F have a natural correspondence with
traversals of F
The preorder traversal of T is equivalent to visiting the nodes of F in
tree preorder.
• If F is empty, then return.
• Visit the root of the first tree of F.
• Traverse the subtrees of the first tree in tree preorder.
• Traverse the remaining trees of F in preorder.
• Inorder traversal of T is equivalent to visiting the nodes of F in tree
inorder, which is defined as:
(1) If F is empty, then return
• Traverse the subtrees of the first tree in tree inorder.
• Visit the root of the first tree.
• Traverse the remaining trees in tree inorder
• we can define the postorder traversal of a forest, F, as:
• If F is empty, then return.
• Traverse the subtrees of the first tree of F in tree postorder.
• Traverse the remaining trees of F in tree postorder.
• Visit the root of the first tree of F
REPRESENTATION DISJOINT SETS
• If Si and Sj are two sets and i != j, then there is no element that is in
both Si and Sj.
Example : three dis joint sets,
S1 = {0, 6, 7, 8)
S2 = {1, 4, 9}
S3 = {2, 3, 5}.
• The minimal operations that can be performed on these sets are
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 Si or Sj).
2. Find(i): Find the set containing the element, i.
Data representation
• with each set name, we keep a pointer to the root of the tree
representing that set.
• If, in addition, each root has a pointer to the set name, we can find
which set an element is in by following the parent links to the root of
its tree and then returning the pointer to the set name.
Array representation of SETS
• The nodes in the trees are numbered 0 through n - 1 we can use the
node’s number as an index.
• This means that each node needs only one field, the index of its
parent, to link to its parent.
• the only data structure that we need is an array.
int parent[MAX-ELEMENTS],
where MAX-ELEMENTS is the maximum number of elements.
Union And Find Operations
• To obtain the union of S1 and S2- Since we have linked the nodes
from children to parent, simply make one of the trees a subtree of
the other
• root nodes have a parent of -1
Simple union-find functions
int simpleFind(int i)
{
for (;parent[i]>=0;i=parent[i])
;
return i;
}
void SimpleUnion(int i,int j)

{
parent[j]=i;
}
Weighting union and Collapsing
find
• Weighting rule for union(i, j): If the number of nodes in tree i is less
than the number in tree j then make j the parent of i; otherwise make
i the parent of j.
• we maintain a count field in the root of every tree.
• If i is a root node, then count[i] equals the number of nodes in that
tree. Since all nodes but the roots of trees have a nonnegative
number in the parent field, we can maintain the count in the parent
field of the roots as a negative number.
void union2(int i, int j)
{
/* union the sets with roots i and j, union the sets with roots i and j, i !=
j, the weighting rule*/
/* parent[i] = -count[i] and parent[j] = -count[j] */

int temp = parent[i] + parent[j];


if (parent[i]> parent[j])
{
parent[i]= j
parent[j]=temp
}
else
{
parent[j] =i;
parent[i] = temp;
}
}
Collapsing rule
• If j is a node on the path from i to its root then make j a child of the
root.
int find2(int i)
{
int root, trail, lead;
for (root= i; parent[root] >=0; root = parent[root] )
;
for (trail = i; trail != root; trail=lead)
{
lead = parent[trail];
parent[trail] =root;
}
return root;
}
GRAPHS
DEFINITION
A graph G consist of two sets V and E
1. V is a finite nonempty set of vertices and
2. E is a set of pairs of vertices these pairs are called edges
A graph can be represents as G = (V, E). V(G) will represent the set of
vertices and E(G) will represent the set of edges of the graph G
Terminologies
1.Undirected Graph: In a undirected graph the pair of vertices
representing an edge is unordered. thus the pairs (u,v) and (v,u)
represent the same edge.
2. 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
3.Self Edges/Self Loops: Edges of the form(v,v) are called self edges or
self loops . It is an edge which starts and ends at the same vertex.
4.Mutigraph: A graph with multiple occurrences of the same edge is
called a multigraph
Complete Graph: An undirected graph with n vertices and exactly n(n-
1)/2 edges is said to be a complete graph.if all pairs of vertices are
connected by an edge.
• 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‘).
• The length of the path is the number of edges in it.
• A simple path :is a path in which all the vertices are distinct.
• 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 of 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
• 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.

• Tree: A tree is a connected acyclic connected graph.


ADT Graph
Graph Representation
The three most commonly used representations are
• 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 is in
E(G).a[i][j]=0 if no such edge in G.
Adjacency list
• every vertex of graph contains list of its adjacent vertices.
• The n rows of the adjacency matrix are represented as n chains.
• The nodes in chain I represent the vertices that are adjacent to vertex
i.
• An array is used to store n vertices and chain is used to store its
adjacencies.
ADJACENCY MULTILIST
• Adjacency Multi-lists are an edge, rather than vertex based graph
representation.
• In the Multi list representation of graph structures has two parts, a
directory of Node information and a set of linked list of edge
information.
Graph Traversal
• Traversal means to visit each node of a graph.
• there are two types of traversals:
1. Depth First traversal
2. Breadth-First traversal
Breadth-First traversal

• Breadth First Search is a traversal technique in which


we traverse all the nodes of the graph in a breadth-
wise motion.
• In BFS, we traverse one level at a time and then jump
to the next level.
• The BFS algorithm makes use of the queue data
structure for implementation
Algorithm for BFS:

• Step 1: Choose any one node randomly, to start


traversing.
Step 2: Visit its adjacent unvisited node.
Step 3: Mark it as visited in the boolean array and
display it.
Step 4: Insert the visited node into the queue.
Step 5: If there is no adjacent node, remove the first
node from the queue.
Step 6: Repeat the above steps until the queue is
empty.
• Algorithm for BFS:
• Step 1: Choose any one node randomly, to start
traversing.
Step 2: Visit its adjacent unvisited node.
Step 3: Mark it as visited in the boolean array and
display it.
Step 4: Insert the visited node into the queue.
Step 5: If there is no adjacent node, remove the first
node from the queue.
Step 6 Repeat the above steps until the queue is empty.
Depth First Search (DFS) Algorithm

• Depth First Search (DFS) algorithm is a recursive


algorithm for searching all the vertices of a graph or
tree data structure.
• This algorithm traverses a graph in a depthward motion
and uses a stack to remember to get the next vertex to
start a search, when a dead end occurs in any iteration.
• Rule 1 − Visit the adjacent unvisited vertex. Mark it as
visited. Display it. Push it in a stack.
• Rule 2 − If no adjacent vertex is found, pop up a vertex
from the stack. (It will pop up all the vertices from the
stack, which do not have adjacent vertices.)
• Rule 3 − Repeat Rule 1 and Rule 2 until the stack is
empty.
Connected Components
• The two fundamental graph traversal methods, DFS (Depth-First
Search) and BFS (Breadth-First Search), serve as building blocks for
developing additional operations.
• The concept of connected components in an undirected graph
revolves around identifying parts of the graph where every pair of
vertices in that part is reachable from each other.
• To determine if an undirected graph is connected (all vertices are
reachable from one another):
1.Start from any vertex (e.g., vertex 0).
2.Perform a DFS (Depth-First Search) or BFS (Breadth-First Search) from
this starting vertex.
3.After the search, check if all vertices were visited:
1. If all vertices are visited, the graph is connected.
2. If some vertices remain unvisited, the graph is not connected.
void connected(void)
{
int i;
for (i = 0; i < n; i++)
{
if (visited[i] == 0)
{
printf("Connected component starting at vertex %d:\n", i);
dfs(i);
printf("\n");
}
}
}
Spanning Trees
• In a connected graph G, DFS (Depth-First Search) or BFS (Breadth-First
Search) starting from any vertex will visit all vertices.
• The search divides the edges into:
1. Tree Edges (T): Edges traversed during the search.
2.Non-Tree Edges (N): Remaining edges
• A spanning tree is a subgraph that Connects all vertices in G and
Contains no cycles.
• Tree edges T form the spanning tree of the graph.
• Spanning trees can be created using either DFS, where the edges form
a tree based on depth-first traversal, or BFS, where the edges form a
tree based on breadth-first traversal.
• Properties of Spanning Trees:
• Contains exactly n−1 edges, where n is the number of vertices.
• Cycles are only formed when non-tree edges are added.
Biconnected Components And
Articulation Points
• An Articulation point is a vertex v of G such that the deletion of v,
together with all edges incident on v, produces a graph, G', that has at
least two connected components
• A Biconnected graph is a connected graph that has no articulation
points.
Terminologies find the
articulation points
1. the sequence in which the vertices are visited during the depth first
search. We call this number the depth first number, or dfn, of the
vertex
2. low(u) is the lowest depth first number that we can reach from u
using a path of descendants followed by at most one back edge
Steps to find an Articulation
point
Steps to find an Articulation point
1. Prepare a DFS spanning tree
2. Write for each node dfn order number or discovery time of each vertex
in DFS
3. Lowest discovery number reachable to each node by
taking any back edge (back edge is edge not included in tree)

4. For each pair of vertices (u,w) where u is parent and w is child,


if low(w) >= dfn(u) then u is an articulation point. Except root this satisfies
all other pair of vertices
For root if it has multiple children then it is an AP
COUNTING BINARY TREES

You might also like