DSA Unit 3 Notes
DSA Unit 3 Notes
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
Trees
BST: Implementation using Arrays
Dr. Shylaja S S
Ms. Kusuma K V
www.pes.edu
Implicit Array Representation of BST
In the implicit array representation, an array element is allocated whether or not it serves to
contain a node of a tree. We must, therefore, flag unused array elements as nonexistent, or
null, tree nodes. This may be accomplished by adding a logical flag field, used, to each node.
Each node then contains two fields: info and used.
typedef struct node
{
int info;
int used;
}NODE;
NODE[p].used is TRUE if node p is not a null node and FALSE if it is a null node.
0
5 info 5 3 7 1 4 8
1 used 1 1 1 1 1 0 1
3 2 7
Position: p 0 1 2 3 4 5 6
3 1 4 4 6 8 Array Representation of
Figure 2: Binary Search Tree Binary Search Tree in Figure 2
#define MAXNODES 50
www.pes.edu
void create(TREE *bst)
{
int ele, wish;
do{
printf("Enter an element\n");
scanf("%d",&ele);
int p=0;
if(p>=MAXNODES)
printf("Insertion not possible\n");
else
{
bst[p].info=ele;
bst[p].used=1;
}
printf("Do you wish to add another\n");
scanf("%d",&wish);
}while(wish);
}
void inorder(TREE* bst, int r)
{
if(bst[r].used)
{
inorder(bst,2*r+1);
printf("%d ",bst[r].info);
inorder(bst,2*r+2);
}
}
www.pes.edu
int main()
{
TREE bst[MAXNODES];
init(bst);
create(bst);
inorder(bst,0);
return 0;
}
Note that under this representation it is always required to check that the range
(NUMNODES) has not been exceeded whenever we move down the tree.
Array Implementation is suitable for a complete binary tree. Otherwise there will be many
vacant positions in between. In such cases we may look into an alternate representation of
tree nodes, i.e., the Linked representation, which makes use of the left and right pointers
along with the info field.
www.pes.edu
Department of Computer Science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
Trees
Binary Search Tree (BST) and its Implementation using Dynamic
Allocation: Insertion
Dr. Shylaja S S
Ms. Kusuma K V
www.pes.edu
Binary Search Tree: is a Binary tree that is either empty or in which every node contains a
key and satisfies the conditions:
• The key in the left side of a child (if it exists) is less than the key in the parent node
• The key in the right side of a child (if it exists) is greater than the key in the parent
node
• The left and right subtrees of the root are again binary search trees
If in case of equal keys we can modify the definition but normally we take distinct keys.
Construct a Binary Search Tree for the elements inserted in the following order:
50, 78, 70, 45, 48, 35, 85
Make 50 Root 78 > 50 Insert Right 70 > 50 Go Right, 70 < 78 Insert Left
70
70 48 70
35 < 50 Go Left, 35 < 45 Insert Left 85 > 50 Go Right, 85 > 78 Insert Right
(35 < 50) 50 50 (85 > 50)
35 48 70 35 48 70 85
www.pes.edu
BST: Linked Representation
In linked representation each node in a binary tree has three fields, the left child
field, information field and the right child field. Pictorially a node used for linked
representation may be as shown in Figure3. If the left subtree is empty then the
corresponding node’s left child field is set to null. If the right subtree is empty then the
corresponding node’s right child field is set to null. If the tree itself is empty the root pointer
is set to null.
Data
OR Left Right
Child Data Child
Left Right
Child Child
5 5
3 7
3 7
1 4 8
Figure 4: Binary Search Tree N
1 4 8
N N N N N N
www.pes.edu
typedef struct tree
{
NODE *root;
}TREE;
pt->root->left=NULL;
pt->root->right=NULL;
do{
printf("Enter an element\n");
temp=(NODE*)malloc(sizeof(NODE));
scanf("%d",&temp->info);
temp->left=NULL;
temp->right=NULL;
q=NULL;
p=pt->root;
while(p!=NULL)
{
q=p;
if(temp->info < p->info)
p=p->left;
else
p=p->right;
}
if(temp->info < q->info)
q->left=temp;
else
q->right=temp;
www.pes.edu
printf("Do you wish to add another? 1/0\n");
scanf("%d",&wish);
}while(wish);
}
void intr(NODE* p)
{
if(p!=NULL)
{
intr(p->left);
printf("%d ",p->info);
intr(p->right);
}
}
int main()
{
TREE tobj;
creat(&tobj);
intrav(&tobj);
return 0;
}
www.pes.edu
Department of Computer Science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
Trees
Binary Search Tree (BST): Deletion
Dr. Shylaja S S
Ms. Kusuma K V
www.pes.edu
Deletion of a Node in Binary Search Tree
Consider the following 3 cases for deletion of a node in Binary Search Tree so that even after
the node is deleted the BST property is preserved.
Case 1: Node with no child (leaf node)
Case 2: Node with 1 child
Case 3: Node with 2 children
5 5
To delete the node with info
7:
3 6 3 6
Set its parent’s left child field
to point to NULL
2 4 8 2 4
Free memory allocated to 8
node with info 7
1 7 9 1 9
5 5
To delete the node with info 4:
1 7 9 1 7 9
www.pes.edu
Case 2: Deletion of a node with one child
Connect the node's parent with node's child node
1 7 9 1
1 7 9
7 9
www.pes.edu
To delete node with info 5 (Way 1: Replace with inorder successor)
5 6 6
3 6 3 6 3 8
2 4 8 2 4 8 2 4 7 9
1 7 9 1 7 9 1
Replace 5 with its Now delete that inorder successor
inorder successor Now case3 has got changed to
case2 (In general may change to
case2 or case1)
5 4 4
3 6 3 6 3 6
2 4 2 4 8 2 8
8
1 7 1 7 9 1 7
9 9
Replace 5 with its Now delete that inorder predecessor
inorder predecessor Now case3 has got changed to case1
(In general may change to case2 or
case1)
www.pes.edu
//BST Deletion
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int info;
struct node *left,*right;
}NODE;
typedef struct tree
{
NODE *root;
}TREE;
NODE* createNode(int e)
{
NODE *temp=malloc(sizeof(NODE));
temp->left=NULL;
temp->right=NULL;
temp->info=e;
return temp;
}
printf("Enter info\n");
scanf("%d",&e);
pt->root=createNode(e);
do{
printf("Enter info\n");
scanf("%d",&e);
q=NULL;
www.pes.edu
p=pt->root;
while(p!=NULL)
{
q=p;
void io(NODE* r)
{
if(r!=NULL)
{
io(r->left);
printf("%d ",r->info);
io(r->right);
}
}
www.pes.edu
NODE* delNode(NODE *r,int ele)
{
NODE *temp,*p;
if(r==NULL)
return r;
r->info=p->info;
r->right=delNode(r->right, p->info);
}
}
return r;
}
void deleteNode(TREE *pt,int e)
{
pt->root=delNode(pt->root,e);
}
www.pes.edu
int main()
{
int e;
TREE t;
init(&t);
create(&t);
inorder(&t);
printf("Enter the element to be deleted\n");
scanf("%d",&e);
deleteNode(&t,e);
printf("After deletion\n");
inorder(&t);
return 0;
}
www.pes.edu
Department of Computer Science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
Trees
Expression Trees
Dr. Shylaja S S
Ms. Kusuma K V
www.pes.edu
Expression Tree
An expression tree is built up from the simple operands and operators of an (arithmetic or
logical) expression by placing the simple operands as the leaves of a binary tree and the
operators as internal nodes.
For each binary operator, the left subtree contains all the simple operands and operators in
the left operand of the given operator, and the right subtree contains everything in the right
operand.
For a unary operator, one of the two subtrees will be empty. We traditionally write some
unary operators to the left of their operands, such as ‘-‘(unary negation) or the standard
functions like log() and cos(). Other unary operators are written on the right, such as the
factorial function ()! or the function that takes the square of a number, () 2. Sometimes
either side is permissible, such as the derivative operator, which can be written as d/dx on
the left, or as ()’ on the right, or the incrementing operator ++ in the C language (where the
actions on the left and right are different). If the operator is written on the left, then in the
expression tree we take its left subtree as empty, so that the operand appear on the right
side of the operator in the tree, just as they do in the expression. If the operator appears on
the right, then its right subtree will be empty, and the operands will be in the left subtree of
the operator.
The expression trees of few simple expressions are shown in Figure 1.
+ log !
a b x n
a+b log x n!
- or
a * < <
b c a b c d
a – (b*c) (a <b) or (c < d )
www.pes.edu
Construction and Evaluation of an Expression Tree
1) Scan the postfix expression till the end, one symbol at a time
a) Create a new node, with symbol as info and left and right link as NULL
b) If symbol is an operand, push address of node to stack
c) If symbol is an operator
i) Pop address from stack and make it right child of new node
ii) Pop address from stack and make it left child of new node
iii) Now push address of new node to stack
2) Finally, stack has only element which is the address of the root of expression tree
//Binary Expression Tree
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define MAX 50
www.pes.edu
int push(STACK *ps,NODE* e)
{
if(ps->top==MAX-1)
return 0;
ps->top++;
ps->s[ps->top]=e;
return 1;
}
return t;
}
www.pes.edu
int main()
{
char postfix[MAX];
STACK sobj;
TREE tobj;
NODE *temp;
init_stack(&sobj);
printf("Enter a valid postfix expression\n");
scanf("%s",postfix);
int i=0;
while(postfix[i] != '\0')
{
temp = (NODE*) malloc(sizeof(NODE));
temp->info = postfix[i];
temp->left=NULL;
temp->right=NULL;
if(isdigit(postfix[i]))
push(&sobj,temp);
else
{
temp->right=pop(&sobj);
temp->left=pop(&sobj);
push(&sobj,temp);
}
i++;
}
tobj.root=pop(&sobj);
printf("%f",eval_tree (&tobj));
return 0;
}
+ *
a * + c
b c a b
(i) a + (b*c) (ii) (a + b)*c
Figure 2: Expressions and their binary tree representations
www.pes.edu
Traversal of the binary expression trees in Figure 2 is as follows:
Figure 2(i): Preorder: +a*bc Inorder: a+b*c Postorder: abc*+
Figure 2(ii): Preorder: *+abc Inorder: a+b*c Postorder: ab+c*
It can be observed that traversing the binary expression tree in preorder and postoder yields
the corresponding prefix and postfix form of the infix expression. But we can see that the
inorder traversal of the binary expression trees doesn’t always yield the infix form of the
expression. This is because the binary expression tree does not contain parentheses, since
the ordering of the operations is implied by the structure of the tree.
struct treenode
{
short int utype;
union{
char operator[MAX];
float val;
}info;
struct treenode *child;
struct treenode *sibling;
};
typedef struct treenode TREENODE;
www.pes.edu
void replace(TREENODE *p)
{
float val;
TREENODE *q,*r;
if(p->utype == operator)
{
q = p->child;
while(q != NULL)
{
replace(q);
q = q->next;
}
}
value = apply(p);
p->utype = OPERAND;
p->val = value;
q = p->child;
p->child = NULL;
while(q != NULL)
{
r = q;
q = q->next;
free(r);
}
}
}
www.pes.edu
Constructing a Tree
void setchildren(TREENODE *p,TREENODE *list)
{
if(p == NULL) {
printf("invalid insertion");
exit(1);
}
if(p->child != NULL) {
printf("invalid insertion");
exit(1);
}
p->child = list;
}
while(q != NULL)
{
r = q;
q = q->next;
}
q = getnode();
q->info = x;
q->next = NULL;
if(r==NULL)
p->child=q;
else
r->next=q;
}
www.pes.edu
Department of Computer Science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
Trees
Threaded Binary Search Tree
Dr. Shylaja S S
Ms. Kusuma K V
www.pes.edu
Threaded binary search tree and its implementation
//Iterative Inorder Traversal Revisited
iterativeInorder(root)
s = emptyStack
p = root
do {
while(p != null)
{ /* Travel down left branches as far as possible saving pointers to
nodes passed in the stack*/
push(s, p)
p = p->left
} //At this point, the left subtree is empty
p = pop(s)
print p ->info //visit the node
p = p ->right //traverse right subtree
} while(!isEmpty(s) or p != null)
If we examine the iterativeInorder function to find out the reason for the need of stack, we
see that the stack is popped when p equals NULL. This happens in two cases:
case (i): The while loop is exited after having been executed one or more times. This implies
that the program has travelled down left branches until it reached a NULL pointer, stacking
a pointer to each node as it was passed. Thus, the top element of the stack is the value of p
before it became NULL. If an auxiliary pointer q is kept one step behind p, the value of q can
be used directly and need not be popped.
case (ii): The while loop is skipped entirely. This occurs after reaching a node with an empty
right subtree, executing the statement p = p -> right, and returning to repeat the body of the
do while loop. At this point, top points to the node whose left subtree was just traversed. If
we had not stacked the pointer to each node as it was passed then we would have lost our
way in this case. So, a node with an empty right subtree, instead of containing a NULL
pointer in its right field, suppose it contained a pointer to the node that would be on top of
the stack at that point in the algorithm (that is, a pointer to its inorder successor), then
there would no longer be a need for the stack, since the last node visited during traversal of
a left subtree points directly to its inorder successor. Such a pointer is called a thread and
must be differentiable from a tree pointer that is used to link a node to its left or right
subtree.
A binary tree in which the right pointer of a node, points to the inorder successor if in case it
is not pointing to the child is called Right In-Threaded Binary Tree. Figure 1 shows a binary
search tree and Figure 2 shows the corresponding right in-threaded binary search tree. The
threads are drawn in dotted lines to differentiate them from tree pointers. Note that the
rightmost node in the tree still has a NULL right pointer, since it has no inorder successor.
www.pes.edu
F F
B G B G
A D I A D I
C E H C E H
Figure 1: Binary Search Tree Figure 2: Right In-Threaded Binary Search Tree
A binary tree in which the left pointer of a node, points to the inorder predecessor if in case
it is not pointing to the child is called Left In-Threaded Binary Tree. A binary tree in which
the right and left pointer of a node, points to the inorder successor and inorder predecessor
respectively if in case it is not pointing to the right and left child respectively is called In-
Threaded Binary Tree. Figure 3 and Figure 4 shows the left in-threaded and in-threaded
binary search tree respectively, corresponding to the binary search tree in Figure 1.
F F
B G B G
A D I A D I
C E H C E H
Figure 3: Left In-Threaded Binary Search Tree Figure 4: In-Threaded Binary Search Tree
www.pes.edu
To implement a right in-threaded binary search tree under the dynamic node
implementation of a binary tree, an extra logical field, rthread is included within each node
to indicate whether or not its right pointer is a thread. Note that, for consistency, the
rthread field of the rightmost node of a tree (that is, the last node in the tree’s inorder
traversal) is also set to TRUE, although its right field remains NULL. Such a node is declared
as follows:
typedef struct node
{
int info;
bool rthread; //TRUE if right is NULL or a non-NULL thread
struct node *left; //Pointer to left child
struct node *right; //Pointer to right child
}NODE;
//C program to demonstrate construction and inorder traversal of right in-threaded binary
search tree
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
www.pes.edu
NODE* createNode(int e)
{
NODE* temp=malloc(sizeof(NODE));
temp->info=e;
temp->left=NULL;
temp->right=NULL;
temp->rthread=1;
return temp;
}
do{
q=NULL;
while(p!=NULL)
{
q=p;
p=p->left;
}
if(q!=NULL)
{
printf("%d ",q->info);
p=q->right;
www.pes.edu
while(q->rthread && p!=NULL)
{
printf("%d ",p->info);
q=p;
p=p->right;
}
}
}while(q!=NULL);
}
pt->root=createNode(e);
do{
printf("Enter info\n");
scanf("%d",&e);
p=pt->root;
q=NULL;
while(p!=NULL)
{
q=p;
if(e<p->info)
p=p->left;
else{
if(p->rthread)
p=NULL;
else
p=p->right;
}
}
if(e < q->info)
setLeft(q,e);
www.pes.edu
else
setRight(q,e);
int main()
{
TREE t;
init(&t);
create(&t);
inOrder(&t);
return 0;
}
www.pes.edu
Department of Computer Science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
Trees
Heap: Implementation using arrays
Dr. Shylaja S S
Ms. Kusuma K V
www.pes.edu
Heap: Concept and Implementation
Definition: A heap can be defined as a binary tree with keys assigned to its nodes (one key
per node) provided the following two conditions are met:
1. The tree's shape requirement - The binary tree is essentially complete, that is, all its levels
are full except possibly the last level, where only some rightmost leaves may be missing
2. The parental dominance requirement - The key at each node is greater than or equal to
the keys at its children. (This condition is considered automatically satisfied for all leaves.)
10 10
1
5 7 5 7
5 7
4 2 2 1
1 6 2 1
In the above figures, only the left most binary tree is a heap. The binary tree in the middle is
not a heap because it doesn’t satisfy the shape requirement. The rightmost binary tree is
not a heap because it doesn’t satisfy the parental dominance requirement.
Properties of Heap
1. There exists exactly one essentially complete binary tree with n nodes. Its height is
equal to ⌊log2n⌋
2. The root of a heap always contains its largest element
3. A node of a heap considered with all its descendants is also a heap
4. A heap can be implemented as an array by recording its elements in the top-down,
left-to-right fashion. It is convenient to store the heap's elements in positions 1
through n of such an array, leaving H[0] either unused or putting there a sentinel
whose value is greater than every element in the heap.
In such a representation,
a) The parental node keys will be in the first ⌊n/2⌋ positions of the array,
while the leaf keys will occupy the last ⌈n/2⌉ positions
b) The children of a key in the array's parental position i (1 <= i <= ⌊n/2⌋) will
be in positions 2i and 2i + 1, and, correspondingly, the parent of a key in position i
(2 <= i <= n) will be in position ⌊n/2⌋
www.pes.edu
Bottom up Heap Construction for the elements: 25, 57, 48, 37, 12, 92, 86, 33
1 25
- 25 57 48 37 12 92 86 33
0 1 2 3 4 5 6 7 8
2 57 48 3
At k = 4, v = 37
Compare 37 with its only child 33
37 > 33, it’s a heap at k=4 4 37 12 5 6 92 86 7
8 33
1 25
- 25 57 48 37 12 92 86 33
0 1 2 3 4 5 6 7 8
2 57 48 3
At k = 3, v = 48
Largest child: 92
Compare 48 with its largest child 4 37 12 5 6 92 86 7
48 < 92, Heapify
8 33
1 25
- 25 57 92 37 12 48 86 33
0 1 2 3 4 5 6 7 8 2 57 92 3
At k = 2, v = 57
Largest child: 37
Compare 57 with its largest child
4 37 12 5 6 48 86 7
57 > 37, It’s a heap at k=2
8 33
www.pes.edu
1 25
- 25 57 92 37 12 48 86 33 2 3
0 1 2 3 4 5 6 7 8
57 92
At k = 1, v = 25
Largest child:92 4 37 12 5 6 48 86 7
Compare 25 with its largest child
25 < 92, Heapify
8 33
1 92
- 92 57 25 37 12 48 86 33
0 1 2 3 4 5 6 7 8
2 57 25 3
At k = 3, v = 25
Largest child:86
Compare 25 with its largest child 4 37 12 5 6 48 86 7
25 < 86, Heapify
8 33
1 92
2 57 86 3
- 92 57 86 37 12 48 25 33
0 1 2 3 4 5 6 7 8
4 37 12 5 6 48 25 7
8 33
www.pes.edu
ALGORITHM HeapBottomUp(H[1…n])
//Constructs a heap from the elements of a given array by the bottom-up algorithm
//Input: An array H[1…n] of orderable items
//Output: A heap H[1…n]
for i = ⌊n/2⌋ downto 1 do
k = i; v=H[k]; heap = false
while not heap and 2*k ≤ n do
j = 2*k
if j < n //there are two children
if H[j] < H[j+1] j = j+1
if v ≥ H[j]
heap = true
else H[k] = H[j]; k = j
H[k] = v
Top down Heap Construction for the elements: 25, 57, 48, 37, 12, 92, 86, 33
Insert 25 Insert 57 Insert 48
25 25 57 57
Heap 25
57 25 48
25 < 57, Heapify Heap Heap
Insert 37
57 57
25 48 37 48
37 25
25 < 37, Heapify Heap
Insert 12
57
37 48
25 12
Heap
www.pes.edu
Insert 92
57 57
37 48 37 92
25 12 92 48
25 12
48<92, Heapify
57<92, Heapify
92
37 57
25 12 48
Heap
Insert 86
92 92
37 57 37 86
25 12 48 86 48 57
25 12
57<86, Heapify Heap
Insert 33
92 92
37 86 37 86
25 12 48 57 33 12 48 57
www.pes.edu
Top down Heap Construction
1. First, attach a new node with key K in it after the last leaf of the existing heap
2. Then sift K up to its appropriate place in the new heap as follows
3. Compare K with its parent's key: if the latter is greater than or equal to K, stop (the
structure is a heap);
4. Otherwise, swap these two keys and compare K with its new parent.
5. This swapping continues until K is not greater than its last parent or it reaches the
root.
6. In this algorithm, too, we can sift up an empty node until it reaches its proper
position, where it will get K’s value.
//Heapify
for(i=1;i<n;i++)
{
elt=a[i];
c=i;
p=(c-1)/2;
while(c>0 && a[p]<elt)
{
a[c]=a[p];
c=p;
p=(c-1)/2;
}
a[c]=elt;
}
www.pes.edu
//display heapified elements
printf("\nElements of heap:\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
//Heap sort
for(i=n-1;i>0;i--)
{
elt=a[i];
a[i]=a[0];
p=0;
if(i==1)
c=-1;
else
c=1;
if(i>2 && a[2]>a[1])
c=2;
while(c>=0 && elt<a[c])
{
a[p]=a[c];
p=c;
c=2*p+1;
if(c+1<=i-1 && a[c]<a[c+1])
c=c+1;
if(c>i-1) c=-1;
}
a[p]=elt;
}
printf("\n");
return 0;
}
www.pes.edu
Department of Computer Science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
Trees
Priority Queue using Heap
Dr. Shylaja S S
Ms. Kusuma K V
www.pes.edu
Priority Queue using Heap
Ascending Heap: Root has the lowest element. Each node’s data is greater than or equal to
its parent’s data. It is also called min heap.
Descending Heap: Root has the highest element. Each node’s data is lesser than or equal to
its parent’s data. It is also called max heap.
Priority Queue is a Data Structure in which intrinsic ordering of the elements does
determine the results of its basic operations.
Ascending Priority Queue: is a collection of items into which items can be inserted
arbitrarily and from which only the smallest item can be removed. If apq is an ascending
priority queue, the operation pqinsert(apq,x) inserts element x into apq and
pqmindelete(apq) removes the minimum element from apq and returns its value.
Descending Priority Queue: is a collection of items into which items can be inserted
arbitrarily and from which only the largest item can be removed. If dpq is a descending
priority queue, the operation pqinsert(dpq,x) inserts element x into dpq and
pqmaxdelete(dpq) removes the maximum element from dpq and returns its value.
The operation empty(pq) applies to both types of priority queue and determines whether a
priority queue is empty. pqmindelete or pqmaxdelete can only be applied to a non empty
priority queue.
Once pqmindelete has been applied to retrieve the smallest element of an ascending
priority queue, it can be applied again to retrieve the next smallest element, and so on. Thus
the operation successively retrieves elements of a priority queue in ascending order
(However, if a small element is inserted after several deletions, the next retrieval will return
that smallest element, which may be smaller than a previously retrieved element). Similarly,
pqmaxdelete retrieves elements of a descending priority queue in descending order. This
explains the designation of a priority queue as either ascending or descending.
The elements of a priority queue need not be numbers or characters that can be compared
directly. They may be complex structures that are ordered on one or several fields. For
example, telephone-book listings consist of names, addresses, and phone numbers and are
ordered by name.
Sometimes the field on which the elements of a priority queue are ordered is not even part
of the elements themselves; it may be a special, external value used specifically for the
purpose of ordering the priority queue. For example, a stack may be viewed as a descending
priority queue whose elements are ordered by time of insertion. Te element that was
inserted last has the greatest insertion-time value and is the only item that can be retrieved.
A queue may similarly be viewed as an ascending priority queue whose elements are
ordered by time of insertion. In both cases the time of insertion is not part of the elements
themselves but is used to order the priority queue.
www.pes.edu
Heap as a Priority queue:
A heap allows a very efficient implementation of a priority queue. Now we will look into
implementation of a descending priority queue using a descending heap. Let dpq be an
array that implicitly represents a descending heap of size k. Because the priority queue is
contained in array elements 0 to k-1, we add k as a parameter of insertion and deletion
operations. Then the operation pqinsert(dpq, k, elt) can be implemented by simply inserting
elt into its proper position in the descending list formed by the path from the root of the
heap (dpq[0]) to the leaf dpq[k]. Once pqinsert(dpq, k, elt) has been executed, dpq becomes
a heap of size k+1.
The insertion is done by traversing the path from the empty position k to position 0 (root),
seeking the first element greater than or equal to elt. When that element is found, elt is
inserted immediately preceding it in the path (i.e., elt is inserted as its child). As each
element less than elt is passed during the traversal, it is shifted down one level in the tree to
make room for elt (This shifting is necessary because we are using the sequential
representation rather than a linked representation of the tree. A new element cannot be
inserted between two existing elements without shifting some existing elements).
This heap insertion operation is also called the siftup operation because elt sifts its way up
the tree. The following algorithm implements pqinsert(dpq, k, elt ). Algorithm for siftup
c = k;
p = (c-1)/2; //p is parent of c
while(c>0 && dpq[p]<elt) {
dpq[c]=dpq[p];
c=p; //advance up the tree
p=(c-1)/2;
}
dpq[c]=elt;
To implement pqmaxdelete(dpq,k), we note that the maximum element is always at the
root of a k-element descending heap. When that element is deleted, the remaining k-1
elements in positions 1 through k-1 must be redistributed into positions 0 through k-2 so
that the resulting array segment from dpq[0] through dpq[k-2] remains a descending heap.
Let adjustheap(root,k) be the operation of rearranging the elements dpq[root+1] through
dpq[k] into dpq[root] through dpq[k-1] so that subtree(root, k-1) forms a descending heap.
Then pqmaxdelete(dpq,k) for a k-element descending heap can be implemented as:
p = dpq[0];
adjustheap(0,k-1);
return(p);
In a descending heap, not only is the root element the largest element in the tree, but an
element in any position p must be the largest in subtree(p,k). Now subtree(p,k) consists of
three groups of elements: its root, dpq[p]; its left subtree, subtree(2*p+1, k); and its right
subtree, subtree(2*p+2, k). dpq[2*p+1], the left child of the root , is the largest element of
the left subtree, and dpq[2*p+2], the right son of the root, is the largest element of the right
www.pes.edu
subtree. When the root dpq[p] is deleted, the larger of these two children must move up to
take its place as te new largest element of subtree(p,k). Then the subtree rooted at position
of the larger element moved up must be readjusted in turn.
Algorithm largechild(p,m)
c = 2*p+1;
if(c+1 <= m && x[c] < x[c+1])
c=c+1;
if(c > m)
return -1;
else
return (c);
www.pes.edu
void init(PQ *pt)
{
pt->n=0;
}
void disp(PQ *pt)
{
int i;
for(i=0;i<pt->n;i++)
printf("%d ",pt->pq[i]);
}
int enqueue(PQ *pt,int e)
{int p,c;
if(pt->n==MAX-1) return 0;
c=pt->n;
p=(c-1)/2;
while(c>0 && pt->pq[p]<e)
{
pt->pq[c]=pt->pq[p];
c=p;
p=(c-1)/2;
}
pt->pq[c]=e;
pt->n=pt->n+1;
return 1;
}
int dequeue(PQ *pt,int *ele)
{
int p,c;
*ele=pt->pq[0];
int elt=pt->pq[pt->n-1];
p=0;
if(pt->n==1)
c=-1;
else c=1;
if(pt->n>2 && pt->pq[2]>pt->pq[1])
c=c+1;
while(c>=0 && elt<pt->pq[c])
{
pt->pq[p]=pt->pq[c];
p=c;
c=2*p+1;
www.pes.edu
if(c+1<pt->n-1 && pt->pq[c+1]>pt->pq[c])
c=c+1;
if(c>=pt->n-1) c=-1;
}
pt->pq[p]=elt;
pt->n=pt->n-1;
return 1;
}
int main()
{
PQ pobj;
int k,choice,ele;
init(&pobj);
do{
printf("1. Enqueue 2 Dequeue 3 Display\n");
printf("Enter the choice");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("enter the information");
scanf("%d",&ele);
enqueue(&pobj,ele);
break;
case 2: k=dequeue(&pobj,&ele);
if(!k) printf("empty");
else
printf("%d dequeues element",ele);
break;
case 3: disp(&pobj);
break;
}
}while(choice<4);
return 0;
}
www.pes.edu
Department of Computer science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
AVL TREES
Abstract
Balanced tree, Need for Balanced tree, definition, AVL Trees, Rotation.
www.pes.edu
Balanced tree
Most operations on a Binary search tree take time directly proportional to the
height of the tree, so it is important to keep the height of the tree small.
A balanced binary search tree is a tree that naturally keeps its height small for
a sequence of insertion and deletion operation.
The tree shown above is balanced because the difference between the heights
of left subtree and right subtree is not more than one.
www.pes.edu
Unbalanced Binary search tree
The tree shown above is unbalanced because the tree right side is 6 leaves
taller than the left hand side.
Why do Binary search trees have to be balanced?
Balanced search tree decreases the number of comparisons required to find a
data element. For example consider a below unbalanced tree, to search for an
element 35 in the below tree seven comparisons is required. Whereas in
balanced tree it requires only 2 comparisons which means the search
performance increased by 50% in a balanced tree.
There are different algorithms used to balance the binary search tree such as
1. AVL trees
2. B-tree
3. Red Black trees
All these data structures force the tree to remain balanced and therefore
guarantee performance.
www.pes.edu
AVL Tree
An AVL tree is height balanced Binary search tree invented by Adelson-Velskii
and Landis. In AVL tree the heights of left and right sub-trees of a root differ by
at-most one. Every node in the AVL tree is associated with balance factor that
is left higher, equal-height or right-higher accordingly ,respectively as the left
subtree has height greater than, equal to, or less than that of the right subtree.
Example of AVL tree:
AVL tree
The tree shown above is an AVL tree as the difference between height of left
subtree and right subtree of every node is at most one.
Example for not an AVL tree
www.pes.edu
The above figure is not an AVL tree as the difference between height of left
subtree and right subtree of root node is 2
An AVL tree has the following properties:
1. The sub-trees of every node differ in height by at most one.
2. Every sub-tree is an AVL tree.
3. Height of AVL tree is always logarthmic in n.
An AVL tree has balance factor calculated at every node. For every node,
height of left and right sub-trees can differ by no more than 1.
The balance factor of any node in an AVL tree is given by:
Balance factor=Height (left subtree)-Height (right subtree)
www.pes.edu
For Example
3-2=1
100
1-1=0
1-2=-1
50
120
1-1=0 0 0
115 135
25 75
0
0
0
65 80
www.pes.edu
1. Left Rotation
The tree is rotated left side to rebalance the tree, when a node is inserted into
the right subtree of the right subtree. For example if the insertion order is 3, 5
and 7 the tree becomes imbalanced after the insertion of node 7. So we
perform Left rotation (rotate in anti- clockwise) to balance the tree.
For example
2. Right Rotation
The tree is rotated right side to rebalance the tree, when a node is inserted in
the left subtree of the left subtree. For Example if the insertion order is 8,6,4
the tree becomes imbalanced after the insertion of node 4 so to balance the
tree we perform Right rotation(rotate clockwise).
3. Left-Right Rotation
In Left-Right Rotation two rotations are performed to balance the tree. The
tree is first rotated on left side and then on right side.
For example in the below unbalanced tree 8 is the root node, 4 is the left child
of 8 and 6 is the Right child of 4. After left rotation on 4 and 6 ,the tree
www.pes.edu
structure looks like as shown below 8 is the root node,6 is the left child of 8
and 4 is the left child of 6
The tree obtained after left rotation is unbalanced so again the tree is rotated
right side inorder to balance the AVL tree. So a balanced tree with 6 as the root
node,4 will become the left child of 6 and 8 is the right child of 8 is obtained.
4. Right-Left Rotation
In Right-Left Rotation, first the tree is rotated right side and then to the left
side.
For Example in the below unbalanced graph, 3 is the root node 7 is the right
child of 3 and 5 is the left child of 7.After applying first right rotation on 7 and
5, then we get a unbalanced tree with 3 as the root node, 5 is the right child of
3 and 7 is the right child of 5.
www.pes.edu
Unbalanced tree Right rotation unbalanced tree
Then the tree is rotated left side inorder to obtain the balanced tree where 5 is
the root node, 3 will be left child of 5 and 7 will be right child of 5.
www.pes.edu
Department of Computer science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
AVL TREES
Abstract
Representation of AVL tree, operations performed on AVL, insertion,
Deletion, Search
www.pes.edu
Representation of AVL Trees
struct NODE
{
int info;
struct NODE *left,*right;
int balancefactor;
};
AVL operations
The Different operations performed on AVL tree are
1. Insert
2. Delete
3. Search
Solution-
Step-01: Insert 60
60
Tree is balanced
www.pes.edu
Step-02: Insert 25
60
25
Tree is balanced
Step-03: Insert 70
60
25 70
Tree is balanced
Step-04: Insert 10
60
25 70
Tree is balanced
10
www.pes.edu
Step-05: Insert 5
As 5< 60, so insert 5 in 60’s left sub tree.
As 5 < 25, so insert 5 in 25’s left sub tree.
As 5 < 10, so insert 5 in 10’s left sub tree.
60
25 70
10
5
Tree is imbalanced
To balance the tree, find the first imbalanced node on the path from the newly
inserted node (node 5) to the root node. The first imbalanced node is node 25.
Now, count three nodes from node 25 in the direction of leaf node. Then, use
AVL tree rotation to balance the tree. After applying RR Rotation
60
10 70
25
5
Tree is balanced
www.pes.edu
Algorithm for insertion:
Step1: insert an element into the tree using Binary search tree method.
Step2: check the balance factor after inserting an element.
Step3: if the balance factor of every node is less than or equal to one then
proceed to next operation. Otherwise tree is imbalanced, perform the suitable
rotation to make it balanced and then proceed to next operation.
2. Deletion operation
Deletion of a node from a tree decreases the height of the tree, which might
lead to unbalanced tree.
The steps of deletion of a node in AVL are –
1. Binary Search Tree deletion algorithm is used to d elete a given
key from the AVL tree.
2. Update the height of the current node of the AVL tree after
the deletion.
3. Calculate the Balance factor at the current node by finding the
difference between height of left sub-tree-height of right sub-
tree.
3a. If the Balance factor > 1 which means the height of the left
sub-tree is greater than the height of the right sub-tree. This
indicates left-left or left-right case. If the Balance factor of left
subtree is greater than 0 then that confirms left-left case, if it
less than 0 then that confirms left-right case. If it is equal to 0,
then this we can either consider this as a left-left case or as a
left-right case. For left-left case, do a right rotation at the
current node. For the left-right case, do a left rotation at left
child of current node followed by a right rotation at the current
node itself.
3b. If Balance Factor < -1 then that means the height of the right
sub-tree is greater than the height of the left sub-tree. This
indicates right-right or right-left case. In this case, if balance
factor of right sub-tree of current node is less than 0 then this
confirms right-right case, if it is greater than 0 then this confirms
www.pes.edu
right-left case. If it is equal to 0, then we can either consider this
as a right-right case or a right-left case. In this implementation,
we will consider this as a right-right case. In right-right case, do a
left rotation at the current node. In right-left case, do a right
rotation at the right child of current node followed by left
rotation at the current node itself.
Delete 60
Delete 50
www.pes.edu
Delete 40
Height is not balanced at node 3, left-left case; perform the right rotation to
balance the tree.
www.pes.edu
Department of Computer science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
GRAPHS
Abstract
Introduction, Properties, Representation of graphs: Adjacency Matrix, Adjacency
List
www.pes.edu
Overview:
Graph G is a pair (V, E), where V is a finite set of vertices and E is a finite set of
edges. We will often denote n = |V|, e = |E|. It consists of set of nodes and arcs.
Each arch in a graph is specified by a pair of nodes.
There are three types of graph
1. Directed graph
2. Undirected graph
3. Weighted graph
1 2
2.
3 4
Directed graph
www.pes.edu
Example.1
V2
V1
Example.2
1 2
3 4
Undirected graph
3 1 1
0 2
4
7
8
2
3
4
3
Weighted graph
www.pes.edu
Graph terminologies:
Adjacent Nodes: When there is an edge from one node to another then these
nodes are called adjacent nodes.
Adjacent Node
Path
Length of the path: Length of the path is the total number of edges included in the
path from the source node to destination node.
1 4
2 3
Undirected graph
www.pes.edu
For example in the above undirected graph ,the path(1,2,3,4) has length 3 since
there are three edges(1,2),(2,3),(3,4). The path 1, 2, 3 has length 2 since there are
2 edges (1, 2), (2, 3).
1 4
2 3
Directed graph
Similarly in the directed graph, the path <1,2,3,4> has length 3 since there are 3
edges <1,2>,<2,3>,<3,4> and the path <1,2,3> has length 2 since there are 2 edges
<1,2>,<2,3>.
Degree: In an undirected graph, the total number of edges linked to a node is
called degree of the node. In digraph there are 2 degrees for every node called
indegree and outdegree.
A B
E D
Degree
In-degree: The in-degree of a node n is the total number of arcs that have n as the
head. For example C is receiving 2 edges so indegree of C is 2.
Outdegree: The outdegree of a node n is the total number of arcs that have n as
the tail. For example outdegree of D is 1.
www.pes.edu
Cycle graph: A path from node to itself be called a cycle or cycle is path in which
first and last vertices are same. A graph with at-least one cycle is called cyclic
graph. A directed acyclic graph is called dag. For example the path<1, 2, 4, 3, and
1> is cycle since the first node and the last node are same. It can be represented as
<1,2>,<2,4>,<4,3>,<3,1>.
Cycle
Acyclic graph: A graph with no cycle is called acyclic graph. Tree is an acyclic graph.
Acyclic graph
Connected: A graph is called connected if there is a path from any vertex to any
other vertex. A tree is defined as connected undirected graph with no cycles.
Example
Connected graph
Disconnected graph: if there exist atleast one vertex in a graph that cannot be
reached from the other vertices in the graph,then such graph is aclled
www.pes.edu
disconnected graph.In the below example vertex 3 cannot be reached by any other
vertices in the graph.
Disconnected graph
Tree
Directed cycle: In directed graph all the edges in a path or cycle have same
direction
Directed cycle
www.pes.edu
Properties of graph (referred from geeks for geeks):
1. Undirected graph
a. The number of possible pairs in an m vertex graph is m*(m-1).
b. The number of edges in an undirected graph is m*(m-1)/2 since the edge
(u, v) is same as the edge(v, u).
Undirected graph
2. Directed graph
a. The number of possible pairs in an m vertex graph is m*(m-1)
b. The number of edges in an directed graph is m*(m-1) since the edge(u,
v) is not the same as the edge(v, u)
c. The number of edges in an directed graph is<=m*(m-1)
Directed graph
Representation of graph
Graph representation is the method to store the graphs in computer memory.
Graph is represented using a set of vertices, and for each vertex, the vertices are
www.pes.edu
directly connected to it by an edge. For a weighted graph weight will be associated
with each edge. The choice of graph representation depends on the application
and the types of operation performed and ease of use.
There are 2 ways of representing the graph
1. Adjacency matrix.
2. Adjacency List.
1. Adjacency Matrix:
Let G= (V, E) be a graph where V is the set of vertices and E is the set of edges. Let
N be the number of vertices in the graph G. The adjacency matrix A of a graph G is
defines as
A[i][j] = 1 if there is an edge from vertex i to j
0 if there is no edge from vertex i to j
The adjacency matrix of a graph is a Boolean square matrix or bit matrix with n
rows and n columns with entries zeros and ones.
In an undirected graph, if there exist an edge (i, j),then A[i][j] and A[j][i] is made
one since (i, j) is similar to (j, i).
In the directed graph if there exist an edge <i,j>, then A[i][j]=1
If there exist no edge between vertex i and j then A[i][j]=0
The matrix is symmetric in case of undirected graph, while it may be asymmetric if
the graph is directed.
www.pes.edu
1. Directed graph
1 2 3 4 5
1 0 1 1 0 0
2 0 0 0 0 1
3 0 0 0 1 0
4 0 1 0 0 1
Directed graph
5 0 0 0 0 0
2. Undirected graph
1 2 3 4 5
1 0 1 1 0 0
2 1 0 0 1 1
3 1 0 0 1 0
4 0 1 1 0 1
5 0 1 0 1 0
Undirected graph
www.pes.edu
3. Weighted graph:
In the weighted graph, distance or cost between the nodes are represented on the
edge cost/distance value specified on the edge between adjacent nodes are
used for representation in the adjacency matrix.
1 2 3 4 5
1 0 2 3 0 0
2 2 0 0 3 4
3 3 0 0 2 0
4 0 3 2 0 4
5 0 4 0 4 0
Weighted graph
www.pes.edu
C representation of graph:
The number of nodes in the graph is constant, that is arcs may be added or deleted
but the nodes may not. A graph with 25 nodes could be declared as
A graph with 25 nodes can be declared as
#define MAX 25
struct node
{
//information associated with each node
};
struct arc
{
int adj;//information associated with each arc
};
struct graph
{
struct node nodes[MAX];
struct arc arcs[MAX][MAX];
};
struct graph g;
Each node in a graph is represented by an integer number from zero to MAX-1,
and the array field nodes represent the appropriate information assigned to each
node. The array field an arcs is a two dimensional array representing every possible
ordered pair of nodes. The value of g.arcs[i][j].adj is either one or zero depending
on whether a node i is adjacent to j.
www.pes.edu
A weighted graph with fixed number of nodes can be declared as
struct arc
{
int adj;
int weight;
};
struct arc g[MAX][MAX];
Drawback of adjacency matrix representation of graph is it requires advance
knowledge of the number of nodes. A new matrix must be created for each
addition and deletion of a node. Adjacency matrix representation is inefficient in
real world situation where a graph may have hundreds of nodes. An alternate
solution to this is to use adjacency list.
www.pes.edu
2. Adjacency Linked List:
Adjacency linked list is an array of n linked list in which every vertex of a graph
contains the list of adjacent vertices
1. Directed graph
Nodes adjacent to 2 is 5
Nodes adjacent to 3 is 4
No Nodes adjacent to 5
Directed graph
www.pes.edu
2. Undirected graph
No Nodes adjacent 5
Undirected graph
www.pes.edu
3. Weighted graph
Weighted graph
www.pes.edu
C representation of adjacency list
Two types of allocated nodes are needed since each graph carries some
information.(arcs does not carry any info).
1. header nodes
arcptr info nextnode
A Sample header node
Each header node contains an info field and two pointers. The first of these to is to
adjacency list of arcs emanating from the graph node, and the second is to next
header node in the graph.
2. Adjacency list nodes
Ndptr nextarc
A sample list node representing an arc
Each arc node contains two pointers, one for nextarc node in adjacency list and the
other to the header node representing the graph that terminates the arc. Refer to
the diagram from textbook T1 8.3.1 page no 543.
Header nodes and list nodes have different formats and must be represented by
different structures. However for simplicity we make assumption that both header
and the list nodes have same format and contain two pointers and a single integer
information field.
www.pes.edu
1. Using array implementation the nodes are declared as
#define MAX 50
struct node
{
int info;
int point;
int next;
};
struct node NODE[MAX];
In the case of header node, node[p] represents a graph node A, node[p].info
represents the information associated with the graph node, node[p].next points to
the next graph node and node[p].point points to the first list node representing an
arc emanating from A. In the case of a list node, node[p] represents an arc <A, B>,
node[p].info represents the weight of arc, node[p].point points to the header node
representing the graph node B.
2. Using dynamic implementation
struct node
{
int info;
strut node *pointer;
struct node *next;
};
struct node *nodeptr;
www.pes.edu
Function to read the adjacency list
void read_adlist(nodeptr a[],int n)
{
int I,j,m ele;
for(i=0;i<n;i++)
{
printf(“enter the number of nodes adjacent to %d:”,i);
scanf(“%d”,&m);
if(m==0) continue;
printf(“Enter the nodes adjacent to %d”,i);
for(j=0;j<m;j++)
{
scanf(“%d”,&ele);
a[i]=insert_rear(ele,a[i]); //Function to insert an element at the rear of the
list
}
}
}
Advantages of using Adjacency list:
1. Adding a new vertex is easy
2. Graphs can be stored in more compact form
www.pes.edu
Department of Computer science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
GRAPHS
Abstract
Implementation of Graph using Adjacency Matrix
www.pes.edu
Implementation of graph using adjacency matrix
C representation of graph:
A graph with 25 nodes can be declared as
#define MAX 25
struct node
{
//information associated with each node
};
struct arc
{
int adj;//information associated with each arc
};
struct graph
{
struct node nodes[MAX];
struct arc arcs[MAX][MAX];
};
struct graph g;
Each node in a graph is represented by an integer number from zero to MAX-1,
and the array field nodes represent the appropriate information assigned to
each node. The array field an arc is a two dimensional array representing every
possible ordered pair of nodes.
www.pes.edu
The different operations performed on adjacency matrix are
1. To add an arc from node1 to node2
void join(int adj[]MAX],int node1,int node2)
{
adj[node1][node2]=TRUE;
}
2. To delete an arc from node1 to node2 if it exists
void remv(int adj[][MAX],int node1,int node2)
{
adj[node1][node2]=FALSE;
}
3. To check whether arc exists between node1 and node2
int adjacent(int adj[][MAX],int node1,int node2)
{
return((adj[node1][node2]==TRUE)?TRUE:FALSE);
}
www.pes.edu
Department of Computer science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
GRAPHS
Abstract
Implementation of Graph using Adjacency List.
www.pes.edu
Implementation of adjacency List:
C representation of adjacency list
1.using array implementation
#define MAX 50
struct node
{
int info;
int point;
int next;
};
struct node NODE[MAX];
2.Using dynamic implementation
struct node
{
int info;
strut node *pointer;
struct node *next;
};
struct node *nodeptr;
Two lists are maintained for adjacency of list. The first list is used to store
information of all the nodes. The second list is used to store the information of
adjacent nodes for each node of a graph.
Header node is used to represent each list, which is assumed to be the first
node of a list as shown below.
www.pes.edu
DATA
Points to the first
node neighboring to
the header node
www.pes.edu
return;
}
R=getnode();
node[r].point=q;
node[r].next=-1;
node[r].info=wt;
(R2<0)?(node[p].point=r):(node[r2].next=r);
}
2. To remove an arc between two nodes if it exists:
Void remv(int p,int q)
{
int r,r2;
r2=-1;
r=node[p].point;
while(r>=0 ** node[r].point !=q)
{
r2=r;
r=node[r].next;
}
If(r>=0)
{
(r2<0)?(node[p].point=node[r].next):(node[r2].next=node[r].next);
freenode(r);
return;
}
www.pes.edu
}
www.pes.edu
return(-1);
}
5. Add a node with specific information to a graph.
int addnode(int *graph,int x)
{
int p;
p=getnode();
node[p].info=x;
node[p].point=-1;
node[p].next=*graph;
*graph=p;
return(p);
}
www.pes.edu
Department of Computer science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
GRAPH TRAVERSAL
Abstract
Traversals, Breadth first search, Depth first search, Implementation,
Advantages, Disadvantages and Applications
www.pes.edu
Graph traversal:
Many graph algorithms requires a systematic way to examine all the nodes
and edges of a graph. Traversing is a process of visiting each and every node of
a graph.
Defining a traversal that relates to the structure of a graph is more complex
than for a list or tree due to following reasons
1. A graph has no first node or root node. Therefore the graph can be traversed
from any node as starting node and once the starting node is selected there
may be few nodes which are not reachable from the starting node. Traversal
algorithm faces the problem of selecting another starting point.
2. In a graph to reach a particular node multiple paths may be available.
3. There is no natural order among the successors of particular node. Thus
there is no prior order in which the successors of a particular node should be
visited.
4. A graph may have more than one predecessor and therefore there is a
possibility for a node to be visited before one of its predecessors. For example
if node A is a successor of nodes B and C, A may be visited after B but before C.
There are two standard algorithms for traversal of graphs. They are:
• Breadth first search (BFS): The BFS will use a queue as an auxiliary structure
to hold nodes for future processing
• Depth first Search (DFS): DFS algorithm traverses a graph in a depth-ward
motion and uses a stack to remember to get the next vertex to start a search,
when dead end occurs in any iteration.
www.pes.edu
Depth First Search:
In Depth first search method, an arbitrary node of a graph is taken as starting
node and is marked as visited. On each iteration, the algorithm proceeds to an
unvisited vertex which is adjacent to the one which is currently in. Process
continues until a vertex with no adjacent unvisted vertex is found. When the
dead end is reached the control returns to the previous node and continues to
visit all the unvisited vertices. The algorithm ends after backing up to the
starting vertex, when the latter being a dead end. The algorithm has to restart
at an arbitrary vertex, if there still remain unvisited vertices.
This process is implemented using stack. A vertex is inserted into the stack
when the vertex is visited for the first time and deletes a vertex when the visit
of the vertex ends.
Iterative procedure to traverse a graph is shown below:
1. Select a node u as a start vertex, push u onto the stack and mark it as
visited.
2. While stack is not empty
For vertex u on top of the stack, find the next immediate adjacent vertex
If v is adjacent
If a vertex v is not visited then
Push it on to stack and mark it as visited
else
Ignore the vertex
End if
Else
Remove the vertex from the stack
End if
End while
3. Repeat step1 and step2 until all the vertices in the graph are visited.
www.pes.edu
f b c g
e
d a
www.pes.edu
Step 1: Insert a source vertex a onto the stack and add a to node visited(S)
Step 2: Push the node adjacent to a that is b onto the stack (alphabetical order)
and add to S if not present in S (Also note that in DFS only one adjacent vertex
which is not visited is considered).
Step 3: push the node adjacent to b, that is d onto stack and add to S if not
present.
Step 4: push the node adjacent to d that is f onto the stack and add to S if not
visited.
Step 5: Since the node adjacent to f is already visited. Pop f from the stack.
Step 6: Since the node adjacent to d is already visited, pop d from the stack.
Step 7: Pop b from the stack.
Step 8: Since there is adjacent node from a to c we add c to stack and S
Step 9: Push the node adjacent to c that is g to stack and add to S.
Step 10: push the node adjacent to g that is e to stack and add to S.
Step 11: Since the node adjacent to e is visited, pop e from the stack.
Step 12: Since the node adjacent to g is visited, pop g from stack
Step 13: Since the node adjacent to c is visited, pop c from stack.
Step 14. Pop a from stack
Thus nodes reachable from a are a, b, c, d, e, f, g.
Disadvantages:
1. It works very fine when search graphs are trees or lattices, but can get struck
in an infinite loop on graphs. This is because depth first search can travel
around a cycle in the graph forever. To eliminate this we keep a list of states
previously visited, and never permit search to return to any of them.
2. We cannot come up with shortest solution to the problem.
www.pes.edu
Breadth First Search: Breadth first search uses the queue data structure for
traversing vertices of the graph. Any node of the graph can act as the starting
node. Using the starting node, all other nodes of the graph are traversed. To
prevent repeated visit to the same node, an array is maintained which keeps
track of visited node.
In breadth first search algorithm the queue is initialized with the starting
vertex and is marked as visited. On each iteration, the algorithm identifies all
the unvisited vertices adjacent to the front vertex, marks them as visited and
adds them to the queue; after that ,the front vertex is removed from the
queue.
www.pes.edu
Step 1: Insert a source vertex a into the queue and add a to node visited(S).
Step 2: Delete an element a from queue and find all the adjacent nodes of .The
nodes adjacent to a are b, c, d and e. Add these nodes to S only if it is not
present in S. So we add b, c, d and e to S
Step 3: Delete b from queue and find all the adjacent nodes to b i.e. a, d, f and
add to S only if it not present in S, so only f is added to S.
Step 4: Delete c from queue, Find all the adjacent nodes to c, and add those
nodes to S if it is not present in S. So add only g to S.
Step 5: Delete d from queue, Find all the adjacent nodes of d and add those to
S if not present. All the adjacent nodes of d is already in S.
Step 6: Delete e from queue, find all the adjacent nodes of e. i.e a and g .Since
g is not in S we add g to S.
Step7: Delete f from queue; find all the nodes adjacent to f. add to S if not
present in S
Step 8: Delete g from queue, find all the adjacent nodes to g. Since all the
adjacent nodes of g are already present in S we don’t add to S.
And the queue is empty so the nodes reachable from Source a: a, b, c, d, e, f, g
Pseudo code:
Insert source u to queue
Mark u as visited
While queue is not empty
Delete a vertex u from queue
Find the vertices v adjacent to u
If v is not visited
Print v
Mark v as visited
Insert v to queue
End if
www.pes.edu
End while
Disadvantages of BFS:
All of the connected vertices must be stored in memory. So consumes more
memory
www.pes.edu
Department of Computer science and Engineering
PES UNIVERSITY
UE19CS202: Data Structures and its Applications (4-0-0-4-4)
APPLICATION
Abstract
Graph representation: Representation of Computer Network Topology,
Different types of Topology
www.pes.edu
Graph representation: Representation of Network Topology:
Graph data structure is mainly in telecommunication and Computer Networks.
Networking uses the Notation G(N,L) instead of G(V,E) for a graph were N is
the set of nodes and L is the set of links.
Topology is the order in which nodes and edges are arranged in the network.
The different types of Network topology are
1. Ring topology (cycle): Ring topology is also called as cycle graph. A simple
graph with two degrees of vertices is called cycle graph. In ring Topology each
vertex is connected to other two vertices, So that they form a network which
looks like a circle or ring.
A B
F C
D
E
Ring topology
www.pes.edu
Adjacency list representation for ring topology
A B F NULLK
B A C NULL
C B D
NULL
D C E NULL
E D NULL
F
F NULL
E A
B C
E D
Star topology
www.pes.edu
Adjacency matrix representation for Star topology
A B C D E
A 0 1 1 1 1
B 1 0 0 0 0
C 1 0 0 0 0
D 1 0 0 0 0
E 1 0 0 0 0
A B NULL
B A NULL
C A NULL
D A NULL
E A NULL
3. Mesh topology: Mesh topology uses a complete graph form. All the nodes in
mesh topology are interconnected. Every node has degree n-1
A B
C
F
E D
Mesh Topology
www.pes.edu
Adjacency matrix for the above graph
A B C D E F
A 0 1 1 1 1 1
B 1 0 1 1 1 1
C 1 1 0 1 1 1
D 1 1 1 0 1 1
E 1 1 1 1 0 1
F 1 1 1 1 1 0
A B C D E F NULL
B A C D E F NULL
A
C A B C D E NULL
D A B C D E NULL
E A B C D F NULL
F A B C D E NULL
www.pes.edu
4. Hybrid Topology
Hybrid topology is the combination of two or more topologies.
D
C
B
E
F
A
Hybrid Topology
www.pes.edu
A B C E F NULL
B A NULL
C A D NULL
D NULL
C E
E
A D NULL
F
A NULL
www.pes.edu