ME DSA Data Structure Lab Record
ME DSA Data Structure Lab Record
COURSE OBJECTIVES
COURSE OUTCOMES
BLOOMS
CO. NO. COURSE OUTCOME
LEVEL
At the end of the course students will be able to
Achieve programming skill to convert a problem to a
CO1 C3
programming logic.
CO2 Apply suitable data structure for the problem in hand. C3
Implement heap and various tree structures like AVL, Red-
CO3 C3
black, B-Tree and segment trees.
CO4 Understand the usage of data structures for geometric problems. C4
CO5 Understand the importance of height balancing in search
C5
structures
LIST OF EXPERIMENTS
1
Ex.No:1 IMPLEMENTATION OF BINARY SEARCH TREES
AIM
A binary search tree (BST) is a tree in which all nodes follows the below mentioned properties
The left sub-tree of a node has key less than or equal to its parent node'skey.
The right sub-tree of a node has key greater than or equal to its parent node's
key.Thus, a binary search tree (BST) divides all its sub-trees into two segments; left sub-
tree and right sub-tree and can be definedas
left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)
ALGORITHM
2
match, return the root pointer.
Step 6: If the key is less than the data value of the root node, repeat the process by
using the left subtree.
Step 7: Otherwise, repeat the same process with the right subtree until either a
match is found or the subtree under consideration becomes an empty tree.
Step 8:Terminate
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>
struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;
}*t,*temp;
int element;
void inorder(struct tree *);
void preorder(struct tree *);
void postorder(struct tree *);
struct tree * create(struct tree *, int);
struct tree * find(struct tree *, int);
struct tree * insert(struct tree *, int);
struct tree * del(struct tree *, int);
struct tree * findmin(struct tree *);
struct tree * findmax(struct tree *);
void main()
{
int ch;
do
{
printf("\n\t\t\tBINARY SEARCH TREE");
printf("\n\t\t\t****** ****** ****");
printf("\nMain Menu\n");
printf("\n1.Create\n2.Insert\n3.Delete\n4.Find\n5.FindMin\n6.FindMax");
printf("\n7.Inorder\n8.Preorder\n9.Postorder\n10.Exit\n");
printf("\nEnter ur choice :");
scanf("%d",&ch);
switch(ch)
{
3
case1:
printf("\nEnter the data:");
scanf("%d",&element);
t=create(t,element);
inorder(t);
break;
case2:
printf("\nEnter the data:");
scanf("%d",&element);
t=insert(t,element);
inorder(t);
case3: break;
printf("\nEnter the data:");
scanf("%d",&element);
t=del(t,element);
inorder(t);
case4: break;
temp=findmin(t);
printf("\nMax element=%d",temp->data);
break;
case6:
temp=findmax(t);
printf("\nMax element=%d",temp->data);
break;
case7:
inorder(t);
break;
case8:
preorder(t);
break;
case9:
postorder(t);
break;
case 10:exit(0);
4
}
}while(ch<=10);
}
if(element==t->data)
{
printf("element already present\n");
}
return t;
}
}
7
postorder(t->rchild);
printf("\t%d",t->data);
}
}
OUTPUT
1.
Cre
ate
2.I
nse
rt
3.D
elet
e
4.F
ind
5.F
ind
Mi
n
6.F
ind
Ma
x
7.I
nor
der
8.P
reo
rde
r
9.P
ost
ord
er
10.
Exi
t
Enter ur choice :1
8
Enter the data:10
10
BINARY SEARCH TREE
****** ****** ****
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :2
9
BINARY SEARCH TREE
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :2
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :2
RESULT
Thus the C program to implement the binary search trees was completed successfully.
10
Ex.No:2 MIN AND MAX HEAPS
AIM
ALGORITHM
Step 1: Start
Step 2: Create a new node at the end of heap.
Step 4: Compare the value of this child node with its parent.
PROGRAM:
#include <stdio.h>
int size = 0;
void swap(int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}
void heapify(int array[], int size, int i)
{
if (size == 1)
{
printf("Single element in the heap");
}
else
{
int largest = i;
11
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && array[l] > array[largest])
largest = l;
if (r < size && array[r] > array[largest])
largest = r;
if (largest != i)
{
swap(&array[i], &array[largest]);
heapify(array, size, largest);
}
}
}
void insert(int array[], int newNum)
{
if (size == 0)
{
array[0] = newNum;
size += 1;
}
else
{
array[size] = newNum;
size += 1;
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
}
}
void deleteRoot(int array[], int num)
{
int i;
for (i = 0; i < size; i++)
{
if (num == array[i])
break;
}
12
swap(&array[i], &array[size - 1]);
size -= 1;
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
}
void printArray(int array[], int size)
{
for (int i = 0; i < size; ++i)
printf("%d ", array[i]);
printf("\n");
}
int main()
{
int array[10];
insert(array, 3);
insert(array, 4);
insert(array, 9);
insert(array, 5);
insert(array, 2);
deleteRoot(array, 4);
printArray(array, size);
}
13
OUT PUT:
Max-Heap array: 9 5 4 3 2
After deleting an element: 9 5 2 3
RESULT:
Thus the ‘C’ program to implement Min and Max heaps was executed successfully.
14
Ex.No:3 LEFTIST HEAPS
AIM
ALGORITHM
Step 2: Put the root with smaller value as the new root
Step 4: Recursively merge its right sub tree and the other tree
PROGRAM:
#include <bits/stdc++.h>
using namespace std;
// Copy constructor.
LeftistHeap::LeftistHeap(LeftistHeap &rhs)
{
root = NULL;
*this = rhs;
}
16
/* Merge rhs into the priority queue.
rhs becomes empty. rhs must be different
from this.*/
void LeftistHeap::Merge(LeftistHeap &rhs)
{
if (this == &rhs)
return;
root = Merge(root, rhs.root);
rhs.root = NULL;
}
17
LeftistNode *tmp = t->left;
t->left = t->right;
t->right = tmp;
}
18
/* Test if the priority queue is logically full.
Returns false in this implementation.*/
bool LeftistHeap::isFull()
{
return false;
}
// Deep copy
LeftistHeap &LeftistHeap::operator =(LeftistHeap & rhs)
{
if (this != &rhs)
{
makeEmpty();
root = clone(rhs.root);
}
return *this;
}
19
//Driver program
int main()
{
LeftistHeap h;
LeftistHeap h1;
LeftistHeap h2;
int x;
int arr[]= {1, 5, 7, 10, 15};
int arr1[]= {22, 75};
h.Insert(arr[0]);
h.Insert(arr[1]);
h.Insert(arr[2]);
h.Insert(arr[3]);
h.Insert(arr[4]);
h1.Insert(arr1[0]);
h1.Insert(arr1[1]);
h.deleteMin(x);
cout<< x <<endl;
h1.deleteMin(x);
cout<< x <<endl;
h.Merge(h1);
h2 = h;
h2.deleteMin(x);
cout<< x << endl;
return 0;
}
OUTPUT:
1
22
5
RESULT:
Thus the program to implement Leftist Heaps was executed successfully.
20
Ex.No:4 IMPLEMENTATION OF AVL TREES
AIM
AVL tree is a self-balanced binary search tree. That means, an AVL tree is also a binary
search tree but it is a balanced tree. A binary tree is said to be balanced, if the difference between
the heights of left and right sub trees of every node in the tree is either -1, 0 or +1. In other
words, a binary tree is said to be balanced if for every node, height of its children differ by at
most one. In an AVL tree, every node maintains a extra information known as balance factor.
An AVL tree is defined as follows...
An AVL tree is a balanced binary search tree. In an AVL tree, balance factor of every node is
-1, 0 or +1.
Balance factor of a node is the difference between the heights of left and right subtrees of that
node. The balance factor of a node is calculated either height of left subtree - height of right
subtree (OR) height of right subtree - height of left subtree.
In AVL tree, after performing every operation like insertion and deletion we need to check the
balance factor of every node in the tree. If every node satisfies the balance factor condition then
we conclude the operation otherwise we must make it balanced. We use rotation operations to
make the tree balanced whenever the tree is becoming imbalanced due to any operation.
Rotation is the process of moving the nodes to either left or right to make tree balanced.
21
There are four rotations and they are classified into two types.
ALGORITHM
Step 1: Start
Step 2: Insert the new element into the tree using Binary Search Tree insertion logic.
Step 3: After insertion, check the Balance Factor of every node.
If the Balance Factor of every node is 0 or 1 or -1 then go for nextoperation.
If the Balance Factor of any node is other than 0 or 1 or -1 then tree is said to be
imbalanced. Then perform the suitable Rotation to make it balanced. And go for
next operation.
Step 4: Compare, the search element with the value of root node in the tree.
If search element is larger, then continue the search process in right subtree.
If we reach to the node with search value, then display "Element is found" and
terminate the function.
Step 5: Stop
22
PROGRAM
#include<stdio.h>
#include<malloc.h>
typedef enum { FALSE ,TRUE } ;
struct node
{
int info;
int balance;
struct node *lchild;
struct node *rchild;
};
struct node *insert (int , struct node *, int *);
struct node* search(struct node *,int);
struct node *insert (int info, struct node *pptr, int *ht_inc)
{
struct node *aptr;
struct node *bptr;
if(pptr==NULL)
{
pptr = (struct node *) malloc(sizeof(structnode));
pptr->info =info;
pptr->lchild = NULL;
pptr->rchild = NULL;
pptr->balance = 0;
*ht_inc = TRUE;
return (pptr);
}
if(info < pptr->info)
{
pptr->lchild = insert(info, pptr->lchild, ht_inc);
if(*ht_inc==TRUE)
{
switch(pptr->balance)
{
case -1: /* Right heavy */
23
pptr->balance = 0;
*ht_inc = FALSE;
break;
case 0: /* Balanced */
pptr->balance = 1;
break;
case 1: /* Left heavy */
aptr = pptr->lchild;
if(aptr->balance == 1)
{
printf("Left to Left Rotation\n");
pptr->lchild= aptr->rchild;
aptr->rchild = pptr;
pptr->balance = 0;
aptr->balance=0;
pptr = aptr;
}
else
{
printf("Left to rightrotation\n");
bptr =aptr->rchild;
aptr->rchild =bptr->lchild;
bptr->lchild =aptr;
pptr->lchild =bptr->rchild;
bptr->rchild =pptr;
if(bptr->balance == 1 )
pptr->balance = -1;
else
pptr->balance = 0;
if(bptr->balance == -1)
aptr->balance = 1;
else
aptr->balance = 0;
bptr->balance=0;
pptr=bptr;
}
*ht_inc = FALSE;
}/*End of switch */
}/*End of if */
}/*End of if*/
if(info > pptr->info)
{
pptr->rchild = insert(info, pptr->rchild, ht_inc);
if(*ht_inc==TRUE)
{
24
switch(pptr->balance)
{
case 1: /* Left heavy */
pptr->balance = 0;
*ht_inc = FALSE;
break;
case 0: /* Balanced */
pptr->balance = -1;
break;
case -1: /* Right heavy */
aptr = pptr->rchild;
if(aptr->balance == -1)
{
printf("Right to Right Rotation\n");
pptr->rchild= aptr->lchild;
aptr->lchild = pptr;
pptr->balance = 0;
aptr->balance=0;
pptr = aptr;
}
else
{
printf("Right to LeftRotation\n");
bptr =aptr->lchild;
aptr->lchild =bptr->rchild;
bptr->rchild =aptr;
pptr->rchild =bptr->lchild;
bptr->lchild =pptr;
if(bptr->balance == -1)
pptr->balance = 1;
else
pptr->balance = 0;
if(bptr->balance == 1)
aptr->balance = -1;
else
aptr->balance = 0;
bptr->balance=0;
pptr = bptr;
}/*End of else*/
*ht_inc = FALSE;
}/*End of switch */
}/*End of if*/
}/*End of if*/
return(pptr);
}/*End of insert()*/
25
void display(struct node *ptr,int level)
{
int i;
if ( ptr!=NULL )
{
display(ptr->rchild, level+1);
printf("\n");
for (i = 0; i < level; i++)
printf(" ");
printf("%d", ptr->info);
display(ptr->lchild, level+1);
}/*End of if*/
}/*End of display()*/
while(1)
{
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the value to be inserted : ");
scanf("%d", &info);
if( search(root,info) == NULL )
root = insert(info, root, &ht_inc);
26
else
printf("Duplicate value ignored\n");
break;
case 2:
if(root==NULL)
{
printf("Tree is empty\n");
continue;
}
printf("Tree is :\n");
display(root, 1);
printf("\n\n");
printf("Inorder Traversal is: ");
inorder(root);
printf("\n");
case 3: break;
default: exit(1);
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
}/*End of main()*/
OUTPUT:
27
RESULT
28
Ex.No:5 RED-BLACK TREES
AIM
ALGORITHM:
Step 1: Start the program.
Step 2: Perform standard BST insertion and make the color of newly inserted nodes as RED.
Step 3: If x is root, change color of x as BLACK (Black height of complete tree increases by 1).
Step 4: Do following if color of x’s parent is not BLACK or x is not root.
If x’s uncle is RED (Grand parent must have been black from property 4)
1. Change color of parent and uncle as BLACK.
2. color of grand parent as RED.
3. Change x = x’s grandparent, repeat steps 2 and 3 for new x.
Step 5: Stop the program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
/* Case : A
Parent of pt is left child
of Grand-parent of
pt */
if (parent_pt == grand_parent_pt->l)
{
/* Case : 1
The uncle of pt is also red
Only Recoloring required */
if (uncle_pt != NULL && uncle_pt->c == 1)
31
{
grand_parent_pt->c = 1;
parent_pt->c = 0;
uncle_pt->c = 0;
pt = grand_parent_pt;
}
else {
/* Case : 2
pt is right child of its parent
Left-rotation required */
if (pt == parent_pt->r) {
leftrotate(parent_pt);
pt = parent_pt;
parent_pt = pt->p;
}
/* Case : 3
pt is left child of its parent
Right-rotation required */
rightrotate(grand_parent_pt);
int t = parent_pt->c;
parent_pt->c = grand_parent_pt->c;
grand_parent_pt->c = t;
pt = parent_pt;
}
}
/* Case : B
Parent of pt is right
child of Grand-parent of
pt */
else {
struct node* uncle_pt = grand_parent_pt->l;
/* Case : 1
The uncle of pt is also red
Only Recoloring required */
if ((uncle_pt != NULL) && (uncle_pt->c == 1))
{
grand_parent_pt->c = 1;
parent_pt->c = 0;
32
uncle_pt->c = 0;
pt = grand_parent_pt;
}
else {
/* Case : 2
pt is left child of its parent
Right-rotation required */
if (pt == parent_pt->l) {
rightrotate(parent_pt);
pt = parent_pt;
parent_pt = pt->p;
}
/* Case : 3
pt is right child of its parent
Left-rotation required */
leftrotate(grand_parent_pt);
int t = parent_pt->c;
parent_pt->c = grand_parent_pt->c;
grand_parent_pt->c = t;
pt = parent_pt;
}
}
}
root->c = 0;
}
// driver code
int main()
{
int n = 7;
33
int a[7] = { 7, 6, 5, 4, 3, 2, 1 };
return 0;
}
OUTPUT:
Inorder Traversal of Created Tree
1 2 3 4 5 6 7
RESULT:
Thus the C program to implement Red-Black Trees was executed successfully.
34
Ex.No:6 IMPLEMENTATION OF BINARY TREES AND OPERATIONS OF BINARY TREES
AIM
A binary tree is a tree data structure in which each node has at most two children,
which are referred to as the left child and the right child.
Insertion:
In binary trees, a new node before insert has to specify 1) whose child it is going to be 2)
mention whether new node goes as left/right child. For example(below image),
To add a new node to leaf node, a new node should also mention whether new node
goes as left/right child.
Deletion:
35
For deletion, only certain nodes in a binary tree can be removed unambiguously.
Suppose that the node to delete is node A. If A has no children, deletion is accomplished by
setting the child of A's parent to null. If A has one child, set the parent of A's child to A's
parent and set the child of A's parent to A's child. In a binary tree, a node with two children
cannot be deleted unambiguously.
ALGORITHM
Step 1: Start.
Step 2: Create a Binary Tree for N
elements. Step 3: Insert an element in
binary tree
Step 4: Traverse the tree in
inorder. Step 5: Traverse the tree
in preorder Step 6: Traverse the
tree in postorder. Step 7: Stop
PROGRAM
#include<stdio
.h>
#include<coni
o.h> struct
node
{
int data;
struct node
*rlink; struct
node *llink;
}*tmp=NULL;
typedef struct node
NODE; NODE
*create();
void preorder(NODE
*); void
inorder(NODE *);
void postorder(NODE
*);
void insert(NODE *);
void main()
{
int n,i,m;
clrs
cr(); 36
do
{
printf(“\n\n0.create\n\n1.insert \n\n2.preorder\n\n3.postorder\n\n4.inorder\n\n5.exit\n\
n”); printf(“\n\nEnter ur choice”);
scanf(“%d”,&m)
; switch(m)
{
case 0:
tmp=create(
); break;
case 1:
insert(t
mp);
break;
case 2:
printf(“\n\nDisplay tree in Preorder traversal\n\
n”); preorder(tmp);
bre
ak;
cas
e
3:
printf(“\n\nDisplay Tree in Postorder\n\
n”); postorder(tmp);
bre
ak;
cas
ee
4:
printf(“\n\nInorder\n\
n”); inorder(tmp);
br
ea
k;
ca
se
5:
exit(0);
}
}
while(n!=5);
getch();
}
void insert(NODE *root)
{
NODE
*newnode;
if(root==NUL
L)
{
newnode=creat
37
e();
root=newnode;
else
{
newnode=creat
e(); while(1)
{
if(newnode->data<root->data)
{
if(root->llink==NULL)
{
root-
>llink=newnode;
break;
}
root=root->llink;
}
if(newnode->data>root->data)
{
if(root->rlink==NULL)
{
root-
>rlink=newnode;
break;
}
root=root->rlink;
}
}
}
}
NODE *create()
{
NODE
*newnode; int
n;
newnode=(NODE*)malloc(sizeof(NOD
E)); printf(“\n\nEnter the Data “);
scanf(“%d”,&n);
newnode->data=n;
newnode-
>llink=NULL;
newnode-
>rlink=NULL;
return(newnode);
}
{
if(tmp!=NULL)
{
postorder(tmp->llink); 38
postorder(tmp->rlink);
printf(“%d->”,tmp-
>data);
}
}
void inorder(NODE *tmp)
{
if(tmp!=NULL)
{
inorder(tmp->llink);
printf(“%d->”,tmp-
>data); inorder(tmp-
>rlink);
}
}
void preorder(NODE *tmp)
{
if(tmp!=NULL)
{
printf(“%d->”,tmp-
>data); preorder(tmp-
>llink); preorder(tmp-
>rlink);
}
}
OUTPUT
0. Creat
1.insert
2.preor
der
3.posto
rder
4.inord
er
5.exit
Enter ur choice 0 39
Enter ur choice3
Inorder
Enter ur choice 5
RESULT
Thus the C program to implement binary tree and its operation was
completed successfully.
40
Ex.No:7 SEGMENT TREES IMPLEMENTAION
AIM
PROGRAM
#include <stdio.h>
#include <math.h>
41
/* A recursive function to update the nodes which have the given
index in their range. The following are parameters
st, si, ss and se are same as getSumUtil()
i --> index of the element to be updated. This index is
in the input array.
diff --> Value to be added to all nodes which have i in range */
void updateValueUtil(int *st, int ss, int se, int i, int diff, int si)
{
// Base Case: If the input index lies outside the range of
// this segment
if (i < ss || i > se)
return;
42
// Update the value in array
arr[i] = new_val;
// If there are more than one elements, then recur for left and
// right subtrees and store the sum of values in this node
int mid = getMid(ss, se);
st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) +
constructSTUtil(arr, mid+1, se, st, si*2+2);
return st[si];
43
}
// Allocate memory
int *st = new int[max_size];
OUTPUT:
Sum of values in given range = 15
Updated sum of values in given range = 22
RESULT
45
Ex.No:8 LINE SEGMENT INTERSECTION
AIM
PROGRAM:
#include <bits/stdc++.h>
using namespace std;
// A point in 2D plane
struct Point
{
int x, y;
};
return false;
}
47
// Find the four orientations needed for general and
// special cases
int o1 = orientation(p1, q1, p2);
int o2 = orientation(p1, q1, q2);
int o3 = orientation(p2, q2, p1);
int o4 = orientation(p2, q2, q1);
// General case
if (o1 != o2 && o3 != o4)
return true;
// Special Cases
// p1, q1 and p2 are collinear and p2 lies on segment p1q1
if (o1 == 0 && onSegment(p1, p2, q1)) return true;
for(auto &pr:mp){
cout<<pr.first<<"\n";
}
return ans;
}
// Driver code
int main() {
50
Segment arr[] = { {{1, 5}, {4, 5}}, {{2, 5}, {10, 1}},{{3, 2}, {10, 3}},{{6, 4}, {9, 4}},{{7, 1}, {8,
1}}};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<isIntersect(arr, n);
return 0;
OUTPUT:
0
RESULT:
Thus the C program to implement the binary search was completed successfully.
51