0% found this document useful (0 votes)
4 views29 pages

DSC++ Unit-V

The document provides an overview of graph theory, including definitions, types of graphs (directed, undirected, weighted), and graph representation methods (adjacency matrix and adjacency list). It also discusses graph traversal algorithms such as Breadth First Search (BFS) and Depth First Search (DFS), as well as binary search trees, AVL trees, B-trees, and Red-Black trees, detailing their properties and operations. The content covers essential concepts and algorithms related to data structures in computer science.

Uploaded by

gaddekavyasree2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views29 pages

DSC++ Unit-V

The document provides an overview of graph theory, including definitions, types of graphs (directed, undirected, weighted), and graph representation methods (adjacency matrix and adjacency list). It also discusses graph traversal algorithms such as Breadth First Search (BFS) and Depth First Search (DFS), as well as binary search trees, AVL trees, B-trees, and Red-Black trees, detailing their properties and operations. The content covers essential concepts and algorithms related to data structures in computer science.

Uploaded by

gaddekavyasree2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIT-V

Graph
A graph can be defined as group of vertices and edges that are used to
connect these vertices. A graph can be seen as a cyclic tree, where the
vertices (Nodes) maintain any complex relationship among them instead of
having parent child relationship.
Definition
A graph G can be defined as an ordered set G(V, E) where V(G) represents
the set of vertices and E(G) represents the set of edges which are used to
connect these vertices.
A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B), (B,C),
(C,E), (E,D), (D,B), (D,A)) is shown in the following figure.

Directed and Undirected Graph


A graph can be directed or undirected. However, in an undirected graph,
edges are not associated with the directions with them. An undirected
graph is shown in the above figure since its edges are not attached with
any of the directions. If an edge exists between vertex A and B then the
vertices can be traversed from B to A as well as A to B.

In a directed graph, edges form an ordered pair. Edges represent a specific


path from some vertex A to another vertex B. Node A is called initial node
while node B is called terminal node.

A directed graph is shown in the following figure.


Graph
Terminology
Path
A path can be defined as the sequence of nodes that are followed in order to
reach some
terminal node V from the initial node U.
Closed Path
A path will be called as closed path if the initial node is same as terminal
node. A path will be closed path if V0=VN.
Simple Path
If all the nodes of the graph are distinct with an exception V0=VN, then such
path P is called as closed simple path.
Cycle
A cycle can be defined as the path which has no repeated edges or
vertices except the first and last vertices.
Connected Graph
A connected graph is the one in which some path exists between every two
vertices (u, v) in V. There are no isolated nodes in connected graph.

Complete Graph
A complete graph is the one in which every node is connected with all other
nodes. A complete graph contain n(n-1)/2 edges where n is the number of
nodes in the graph.
Weighted Graph
In a weighted graph, each edge is assigned with some data such as length
or weight. The weight of an edge e can be given as w(e) which must be a
positive (+) value indicating the cost of traversing the edge.
Digraph
A digraph is a directed graph in which each edge of the graph is associated
with some direction and the traversing can be done only in the specified
direction.
Loop
An edge that is associated with the similar end points can be called as Loop.
Adjacent Nodes
If two nodes u and v are connected via an edge e, then the nodes u
and v are called as neighbours or adjacent nodes.
Degree of the Node
A degree of a node is the number of edges that are connected with that
node. A node with degree 0 is called as isolated node.

Graph Representation
By Graph representation, we simply mean the technique which is to be
used in order to store some graph into the computer's memory.

There are two ways to store Graph into the computer's memory. In this part of
this tutorial, we discuss each one of them in detail.
1. Sequential Representation
In sequential representation, we use adjacency matrix to store the
mapping represented by vertices and edges. In adjacency matrix, the
rows and columns are represented by the graph vertices. A graph having
n vertices, will have a dimension n x n.
An entry Mij in the adjacency matrix representation of an undirected graph G
will be 1 if there exists an edge between Vi and Vj.
An undirected graph and its adjacency matrix representation is shown in the
following figure.

in the above figure, we can see the mapping among the vertices (A, B, C,
D, E) is represented by using the adjacency matrix which is also shown in
the figure.

There exists different adjacency matrices for the directed and undirected
graph. In directed graph, an entry Aij will be 1 only when there is an edge
directed from Vi to Vj.

A directed graph and its adjacency matrix representation is shown in the


following figure.
Representation of weighted directed graph is different. Instead of filling the
entry by 1, the Non- zero entries of the adjacency matrix are represented by
the weight of respective edges.
The weighted directed graph along with the adjacency matrix representation is
shown in the following figure.

Linked Representation
In the linked representation, an adjacency list is used to store the Graph into
the computer's memory.

Consider the undirected graph shown in the following figure and check the
adjacency list representation.

An adjacency list is maintained for each node present in the graph which
stores the node value and a pointer to the next adjacent node to the
respective node. If all the adjacent nodes are traversed then store the NULL
in the pointer field of last node of the list. The sum of the lengths of
adjacency lists is equal to the twice of the number of edges present in an
undirected graph.
Consider the directed graph shown in the following figure and check the
adjacency list representation of the graph.
In a directed graph, the sum of lengths of all the adjacency lists is equal to the
number of edges present in the graph.

In the case of weighted directed graph, each node contains an extra field
that is called the weight of the node. The adjacency list representation of
a directed graph is shown in the following figure.

Graph Traversal Algorithm

In this part of the tutorial we will discuss the techniques by using which, we can
traverse all the vertices of the graph.

Traversing the graph means examining all the nodes and vertices of the
graph. There are two standard methods by using which, we can traverse the
graphs. Lets discuss each one of them in detail.

o Breadth First Search


o Depth First Search
Breadth First Search (BFS) Algorithm
Breadth first search is a graph traversal algorithm that starts traversing the
graph from root node and explores all the neighbouring nodes. Then, it
selects the nearest node and explore all the unexplored nodes. The
algorithm follows the same process for each of the nearest node until it finds
the goal.
The algorithm of breadth first search is given below. The algorithm starts
with examining the node A and all of its neighbours. In the next step, the
neighbours of the nearest node of A are explored and process continues in
the further steps. The algorithm explores all neighbours of all the nodes and
ensures that each node is visited exactly once and no node is visited twice.

Algorithm
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
Depth First Search (DFS) Algorithm
Depth first search (DFS) algorithm starts with the initial node of the graph G,
and then goes to deeper and deeper until we find the goal node or the node
which has no children. The algorithm, then backtracks from the dead end
towards the most recent node that is yet to be completely unexplored.

The data structure which is being used in DFS is stack. The process is
similar to BFS algorithm. In DFS, the edges that leads to an unvisited node
are called discovery edges while the edges that leads to an already visited
node are called block edges.

Algorithm
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 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
Binary Search Trees:
In a binary tree, every node can have a maximum of two children but there
is no need to maintain the order of nodes basing on their values. In binary
tree, the elements are arranged in the order they arrive to the tree from
top to bottom and left to right.
A binary tree has the following time complexities...

 Search Operation - O(n)


 Insertion Operation - O(1)
 Deletion Operation - O(n)

To enhance the performance of binary tree, we use special type of binary tree
known as Binary Search Tree

Suppose T is a binary tree. Then T is called a binary searchNtree if each Node


of tree T has
the following property: The value at N is greater than every value
t in the left
sub ree of N and is less than every value in the right subtree of N.

In this tree, left subtreeyof ever node contains nodes with smaller values and
right subtree of
every node contains larger values.

Search Operation ina In a binary search tree, the se


BST
rch operation is performed with O(log n)time
complexity. The
search operation is performed as follows...

Step 1 - Read the search element from the user.


Step 2 - Compare the search element with the value of root node in the tree.
Step 3 - If both are matched, then display "Given node is found!!!" and terminate
the function
Step 4 - If both are not matched, then check whether search element is smaller
or larger than that node value.
Step 5 - If search element is smaller, then continue the search process in left
subtree.
Step 6- If search element is larger, then continue the search process in right
subtree.
Step 7 - Repeat the same until we find the exact element or ment is compared
until the search ele with the leaf node
Step 8 - If we reach to the node having the value equal to the search value then
display "Element is found" and terminate the function.
Step 9 - If we reach to the leaf node and if it is also not matched with the
search element, then display "Element is not found" and terminate the function.

Algorithm for Insertion


a) Compare ITEM with the root node N of the tree.

i) If ITEM< N , Proceed to the left Child of N.

ii) If ITEM > N, proceed to the right child of N.

b) Repeat Step (a) until one of the following occurs:

i) We meet a node N such that ITEM=N. In this case the search


is successful

ii) We meet an empty subtree, which indicates that the


and we insert
search is unsuccessful, ITEM in place of the empty subtree

Example
Construct a Binary Search Tree by inserting the followings
...
sequence of number
10,12,5,4,20,8,7,15 and 13
Above elements are inserted into a Binary Search Tree as
follows...
Deletion Operation in BST

In a binary search tree, the deletion operation is performed with O(log


n)time complexity. Deleting a node from Binary search tree includes following
three cases...
Case 1: Deleting a Leaf node (A node with no
children) Case 2: Deleting a node with one
child
Case 3: Deleting a node with two children

Case 1: Deleting a leaf node


We use the following steps to delete a leaf node from BST...
Step 1 - Find the node to be deleted using search operation
Step 2 - Delete the node using free function (If it is a leaf) and terminate the
function.

Case 2: Deleting a node with one child


We use the following steps to delete a node with one child from BST...
Step 1 - Find the node to be deleted using search operation
Step 2 - If it has only one child then create a link between its parent node
and child node.
Step 3 - Delete the node using free function and terminate the function.
Case 3: Deleting a node with two children

We use the following steps to delete a node with two children from BST...
Step 1 - Find the node to be deleted using search operation
Step 2 - If it has two children, then find the largest node in its
left subtree (OR) the smallest node in its right subtree.
Step 3 - Swap both deleting node and node which is found in the above
step.
Step 4 - Then check whether deleting node came to case 1 or case 2or else
goto step 2
Step 5 - If it comes to case 1, then delete using case 1 logic.
Step 6- If it comes to case 2, then delete using case 2 logic.
Step 7 - Repeat the same process until the node is deleted from the tree.

AVL tree
In early 60’s of 19th century E.M. Landis and G.M. Adelson- Velsky formed a
self - balancing BST (binary search tree) data structure. This data structure is
known by AVL tree.
An AVL tree is a binary search tree with self – balancing condition. The
condition assures that the difference between the height of left and right
sub tree cannot be greater than one. This difference between left sub tree
and right sub tree is known as Balance Factor
Balance Factor= Height of Left Subtree - Height of
Right Subtree

If the value of balance factor is greater than one then the tree is balanced
using some rotational techniques and these rotational techniques are known
as AVL rotation.

AVL tree have following rotation techniques to balance itself.


 Left rotation
 Right rotation
 Left - Right rotation
 Right - Left rotation

In above techniques the first two are single rotations and next two are double
rotations.

Left Rotation
If the node is inserted into the right subtree of the right subtree then we can

perform the left rotation to balance the unbalanced tree.


In above figure we can see the left rotation of the tree. Using this technique
we balance an unbalance tree of height 2.

Right Rotation
If the node is inserted into the left subtree of the leftsubtree then we can
perform the right rotation to balance the unbalanced tree.
In above figure we can see the right rotation of the tree. Using this technique
we balance an unbalance tree of height 2.

Left Right Rotation (LR Rotation)

The LR Rotation is sequence of single left rotation followed by single right


rotation. In LR
Rotation, at first every node moves one position to left and one
tfrom the current peration in AVL
o
position to righ position. To understand LR Rotation, let us
consider the following insertion Tree...

Right Left Rotation (RL Rotation)

The RL Rotation is sequence of single right rotation followed by single left


rotation. In RL
Rotation, at first every node moves one position to right and from the current
o
one position to lef position. To understand RL Rotation, let us peration in AVL
consider the following insertion Tree...
B TREE
A B tree is designed to store sorted data and allows search, insertion and
deletion operation to be performed in logarithmic time. As In multiway
search tree, there are so many nodes which have left subtree but no right
subtree. Similarly, they have right subtree but no left subtree. As is known,
access time in the tree is totally dependent on the level of the tree. So our
aim is to minimize the access time which can be through balance tree only.
For balancing the tree each node should contain n/2 keys. So the B tree
of order n can be defined as:
 All leaf nodes should be at same level.
 All leaf nodes can contain maximum n-1 keys.
 The root has at least two children.
 The maximum number of children should be n and each node can
contain k keys. Where, k<=n-1.
 Each node has at least n/2 and maximum n nonempty children.
 Keys in the non-leaf node will divide the left and right sub-tree where
the value of left subtree keys will be less and value of right subtree
keys will be more than that particular key.
Red Black Tree
A Red Black Tree is a type of self-balancing binary search tree, in which
every node is colored with a red or black. The red black tree satisfies all the
properties of the binary search tree but there are some additional
properties which were added in a Red Black Tree. The height of a Red-Black
tree is O(Logn) where (n is the number of nodes in the tree).
Properties of Red Black Tree
 The root node should always be black in color.
 Every null child of a node is black in red black tree.

 The children of a red node are black. It can be possible that parent
of red node is black node.
 All the leaves have the same black depth.
 Every simple path from the root node to the (downward) leaf node
contains the same number of black nodes.

Representation of Red Black Tree

While representing the red black tree color of each node should be shown.
In this tree leaf nodes are simply termed as null nodes which means they
are not physical nodes. It can be checked easily in the above-given tree
there are two types of node in which one of them is red and another one is
black in color. The above-given tree follows all the properties of a red black
tree that are
 It is a binary search tree.
 The root node is black.
 The children’s of red node are black.
 All the root to external node paths contain same number of black nodes.
Example: Consider path 75-90-80-88-null and 75-40-30-null in both these
paths 3 black nodes are there.

Advantages of Red Black Tree


 Red black tree are useful when we need insertion and deletion relatively
frequent.
 Red-black trees are self-balancing so these operations are guaranteed to
be O(logn).
 They have relatively low constants in a wide variety of scenarios.

Comparison of Search Trees

The comparison of search trees is performed based on the Time complexity


of search, insertion and deletion operations in search trees. The following
table provides the Time complexities of search trees. These Time
complexities are defined for 'n' number of elements.

Search tree Average case Worst case

Insert Delete Search Insert Delete Search

Binary
O(log O(log O(log n) O(n) O(n) O(n)
Search Tree n) n)

O(log O(log O(log O(log


AVL Tree O(log2 n) O(log2
2 n) 2 n) 2 n) 2 n)
n)

O(log O(log O(log n) O(n) O(n) O(n)


B tree
n) n)
O(log O(log O(log n) O(n) O(n) O(n)
Red Black Tree
n) n)

You might also like