You are on page 1of 74

M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program -1 Binary Search Tree Program */

#include<stdlib.h>
#include<conio.h>
#include<stdio.h>

struct tree {
int info;
struct tree *left;
struct tree *right;
};

struct tree *insert(struct tree *,int);


void inorder(struct tree *);
void postorder(struct tree *);
void preorder(struct tree *);
struct tree *delet(struct tree *,int);
struct tree *search(struct tree *);

int main(void) {
struct tree *root;
int choice, item,item_no;
root = NULL;

do {
do {
printf("\n \t 1. Insert in Binary Tree ");
printf("\n\t 2. Delete from Binary Tree ");
printf("\n\t 3. Inorder traversal of Binary tree");
printf("\n\t 4. Postorder traversal of Binary
tree");

1|Page
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

printf("\n\t 5. Preorder traversal of Binary tree");


printf("\n\t 6. Search and get to know left child
and right child ");
printf("\n\t 7. Exit ");
printf("\n\t Enter choice : ");
scanf(" %d",&choice);
if(choice<1 || choice>7)
printf("\n Invalid choice - try again");
}while (choice<1 || choice>7);
switch(choice) {
case 1:
printf("\n Enter new element: ");
scanf("%d", &item);
root= insert(root,item);
printf("\n root is %d",root->info);
printf("\n Inorder traversal of binary tree is : ");
inorder(root); break;
case 2:
printf("\n Enter element to be deleted : ");
scanf(" %d",&item_no);
root=delet(root,item_no);
inorder(root); break;
case 3:
printf("\n Inorder traversal of binary tree is : ");

inorder(root); break;
case 4:
printf("\n Postorder traversal of binary tree is : ");

postorder(root); break;
case 5:
printf("\n Preorder traversal of binary tree is : ");

preorder(root); break;

2|Page
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

case 6:
printf("\n Search operation in binary tree ");
root=search(root); break;
default:
printf("\n End of program ");
}
}while(choice !=7);
return(0);
}
void inorder(struct tree *root) {
if(root != NULL) {
inorder(root->left);
printf(" %d",root->info);
inorder(root->right);
}
}
void postorder(struct tree *root) {
if(root != NULL) {
postorder(root->left);
postorder(root->right);
printf(" %d",root->info);
}
}
void preorder(struct tree *root) {
if(root != NULL) {
printf(" %d",root->info);
preorder(root->left);
preorder(root->right);
}
}

3|Page
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

struct tree *insert(struct tree *root, int x) {


if(!root) {
root=(struct tree*)malloc(sizeof(struct tree));
root->info = x; root->left = NULL; root->right = NULL;
return(root);
}
if(root->info > x)
root->left = insert(root->left,x);
else {
if(root->info < x)
root->right = insert(root->right,x);
}
return(root);
}

struct tree *delet(struct tree *ptr, int x) {


struct tree *p1,*p2;
if(!ptr) {
printf("\n Node not found ");
return(ptr);
}
else {
if(ptr->info < x)
ptr->right = delet(ptr->right, x);
else if (ptr->info >x) {
ptr->left=delet(ptr->left,x);
return ptr;
}
else {
if(ptr->info == x)
{

4|Page
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

if(ptr->left == ptr->right)
/*i.e., a leaf node*/ {
free(ptr);
return(NULL);
}
else if(ptr->left==NULL)
/* a right subtree */ {
p1=ptr->right;
free(ptr);
return p1;
}
else if(ptr->right==NULL)
/* a left subtree */ {
p1=ptr->left;
free(ptr);
return p1;
}
else {
p1=ptr->right;
p2=ptr->right;
while(p1->left != NULL)
p1=p1->left;
p1->left=ptr->left;
free(ptr);
return p2;
}
}
}
}
return(ptr);
}

5|Page
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

struct tree *search(struct tree *root) {


int no,i,ino;
struct tree *ptr, *parent, *l_child, *r_child;
ptr=root;
printf("\n Enter the element to be searched :");
scanf(" %d",&no);

while(ptr) {
parent = ptr;
l_child = ptr->left;
r_child = ptr->right;
if(no>ptr->info)
ptr=ptr->right;
else if(no<ptr->info)
ptr=ptr->left;
else
break;
}

if(ptr->left != NULL && ptr->right != NULL) {


printf("\n Element %d which was searched is found and its left
child value is %d right child is %d",no, l_child->info, r_child->info);
}

else if(ptr->left==NULL || ptr->right==NULL)


{
if(ptr->left==NULL && ptr->right==NULL)
printf("\n Element %d which was searched is found to be
leaf node and its left child is NULL and right child is NULL",no);

if(ptr->left == NULL)
printf("\n Element %d which was searched is found and its
left child is NULL and right child is %d",no, r_child->info);

if(ptr->left == NULL)
printf("\n Element %d which was searched is found and its
left child is %d and right child is NULL",no, l_child->info);
}
else
printf("\n Element %d does not exist in the binary tree",no);
return(root);
}

6|Page
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program – 2 a) Recursive C program for merge sort */


#include<stdlib.h>
#include<stdio.h>
void merge(int arr[], int l, int m, int r);

void mergeSort(int arr[], int l, int r)


{
if (l < r)
{
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}

void merge(int arr[], int l, int m, int r)


{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];

i = 0; j = 0;
k = l;

7|Page
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

while (i < n1 && j < n2)


{
if (L[i] <= R[j])
{
arr[k] = L[i]; i++;
}
else
{
arr[k] = R[j]; j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++; k++;
}
while (j < n2)
{
arr[k] = R[j];
j++; k++;
}
}

void printArray(int A[], int size)


{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}

8|Page
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}

9|Page
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program -2 b) Iterative C Program for Heap Sort */


#include<stdio.h>
#include<conio.h>
void buildMaxHeap(int arr[], int n) {
int temp;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[(i - 1) / 2]) {
int j = i;
while (arr[j] > arr[(j - 1) / 2]){
temp = arr[j];
arr[j] = arr[(j - 1) / 2];
arr[(j - 1) / 2] = temp;
j = (j - 1) / 2;
}
}
}
}
void heapSort(int arr[], int n){
int temp; buildMaxHeap(arr, n);
for (int i = n - 1; i > 0; i--) {
temp = arr[0]; arr[0] = arr[i]; arr[i] = temp;
int j = 0, index;
do{
index = (2 * j + 1);
if (arr[index] < arr[index + 1] && index < (i - 1))
index++;
if (arr[j] < arr[index] && index < i) {
temp=arr[j]; arr[j] = arr[index];
arr[index] = temp;
}
j = index;
} while (index < i);
} }

10 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

int main()
{
int arr[] = {10, 20, 15, 17, 9, 21};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Given array: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);

printf("\n\n");

heapSort(arr, n);

// print array after sorting


printf("Sorted array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);

return 0;
}

11 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program–2 c) Recursive C program for Quick sort */


#include<stdio.h>
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition (int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high- 1; j++)
{
if (arr[j] < pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
12 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

void printArray(int arr[], int size)


{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}

// Driver program to test above functions


int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);
printf("Sorted array: n");
printArray(arr, n);
return 0;
}

13 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program – 3 C++ Program to implement B- Tree */


#include<iostream>
using namespace std;

class BTreeNode
{
int *keys;
int t;
BTreeNode **C;
int n;
bool leaf;
public:
BTreeNode(int _t, bool _leaf);
void traverse();
BTreeNode *search(int k);
int findKey(int k);
void insertNonFull(int k);
void splitChild(int i, BTreeNode *y);
void remove(int k);
void removeFromLeaf(int idx);
void removeFromNonLeaf(int idx);
int getPred(int idx);
int getSucc(int idx);
void fill(int idx);
void borrowFromPrev(int idx);
void borrowFromNext(int idx);
void merge(int idx);

friend class BTree;


};

14 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

class BTree
{
BTreeNode *root;
int t;
public:
BTree(int _t) {
root = NULL;
t = _t;
}
void traverse() {
if (root != NULL) root->traverse();
}
BTreeNode* search(int k) {
return (root == NULL)? NULL : root->search(k);
}
void insert(int k);
void remove(int k);
};
BTreeNode::BTreeNode(int t1, bool leaf1) {
t = t1; leaf = leaf1;
keys = new int[2*t-1];
C = new BTreeNode *[2*t];
n = 0;
}
int BTreeNode::findKey(int k) {
int idx=0;
while (idx<n && keys[idx] < k)
++idx;
return idx;
}

15 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

void BTreeNode::remove(int k){


int idx = findKey(k);
if (idx < n && keys[idx] == k) {
if (leaf) removeFromLeaf(idx);
else removeFromNonLeaf(idx);
}
else {
if (leaf) {
cout << "The key "<< k <<" is does not exist in the tree\n";
return;
}
bool flag = ( (idx==n)? true : false );
if (C[idx]->n < t) fill(idx);
if (flag && idx > n) C[idx-1]->remove(k);
else C[idx]->remove(k);
}
return;
}
void BTreeNode::removeFromLeaf (int idx) {
for (int i=idx+1; i<n; ++i)
keys[i-1] = keys[i];
n--; return;
}
void BTreeNode::removeFromNonLeaf(int idx){
int k = keys[idx];
if (C[idx]->n >= t) {
int pred = getPred(idx);
keys[idx] = pred;
C[idx]->remove(pred);
}

16 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

else if (C[idx+1]->n >= t) {


int succ = getSucc(idx);
keys[idx] = succ;
C[idx+1]->remove(succ);
}
else {
merge(idx);
C[idx]->remove(k);
}
return;
}

int BTreeNode::getPred(int idx) {


BTreeNode *cur=C[idx];
while (!cur->leaf)
cur = cur->C[cur->n];
return cur->keys[cur->n-1];
}
int BTreeNode::getSucc(int idx) {
BTreeNode *cur = C[idx+1];
while (!cur->leaf)
cur = cur->C[0];
return cur->keys[0];
}
void BTreeNode::fill(int idx) {
if (idx!=0 && C[idx-1]->n>=t)
borrowFromPrev(idx);
else if (idx!=n && C[idx+1]->n>=t)
borrowFromNext(idx);
else {

17 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

if (idx != n)
merge(idx);
else
merge(idx-1);
}
return;
}
void BTreeNode::borrowFromPrev(int idx){
BTreeNode *child=C[idx];
BTreeNode *sibling=C[idx-1];
for (int i=child->n-1; i>=0; --i)
child->keys[i+1] = child->keys[i];
if (!child->leaf) {
for(int i=child->n; i>=0; --i)
child->C[i+1] = child->C[i];
}
child->keys[0] = keys[idx-1];
if(!child->leaf)
child->C[0] = sibling->C[sibling->n];
keys[idx-1] = sibling->keys[sibling->n-1];
child->n += 1;
sibling->n -= 1;
return;
}
void BTreeNode::borrowFromNext(int idx) {
BTreeNode *child=C[idx];
BTreeNode *sibling=C[idx+1];
child->keys[(child->n)] = keys[idx];
if (!(child->leaf))
child->C[(child->n)+1] = sibling->C[0];

18 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

keys[idx] = sibling->keys[0];
for (int i=1; i<sibling->n; ++i)
sibling->keys[i-1] = sibling->keys[i];
if (!sibling->leaf) {
for(int i=1; i<=sibling->n; ++i)
sibling->C[i-1] = sibling->C[i];
}
child->n += 1;
sibling->n -= 1;
return;
}
void BTreeNode::merge(int idx) {
BTreeNode *child = C[idx];
BTreeNode *sibling = C[idx+1];
child->keys[t-1] = keys[idx];
for (int i=0; i<sibling->n; ++i)
child->keys[i+t] = sibling->keys[i];
if (!child->leaf) {
for(int i=0; i<=sibling->n; ++i)
child->C[i+t] = sibling->C[i];
}
for (int i=idx+1; i<n; ++i)
keys[i-1] = keys[i];
for (int i=idx+2; i<=n; ++i)
C[i-1] = C[i];
child->n += sibling->n+1;
n--;
delete(sibling);
return;
}

19 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

void BTree::insert(int k){


if (root == NULL) {
root = new BTreeNode(t, true);
root->keys[0] = k;
root->n = 1;
}
else {
if (root->n == 2*t-1) {
BTreeNode *s = new BTreeNode(t, false);
s->C[0] = root;
s->splitChild(0, root);
int i = 0;
if (s->keys[0] < k)
i++;
s->C[i]->insertNonFull(k);
root = s;
}
else
root->insertNonFull(k);
}
}
void BTreeNode::insertNonFull(int k){
int i = n-1;
if (leaf == true) {
while (i >= 0 && keys[i] > k) {
keys[i+1] = keys[i]; i--;
}
keys[i+1] = k;
n = n+1;
}

20 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

else {
while (i >= 0 && keys[i] > k)
i--;
if (C[i+1]->n == 2*t-1) {
splitChild(i+1, C[i+1]);
if (keys[i+1] < k)
i++;
}
C[i+1]->insertNonFull(k);
}
}
void BTreeNode::splitChild(int i, BTreeNode *y) {
BTreeNode *z = new BTreeNode(y->t, y->leaf);
z->n = t - 1;
for (int j = 0; j < t-1; j++)
z->keys[j] = y->keys[j+t];
if (y->leaf == false) {
for (int j = 0; j < t; j++)
z->C[j] = y->C[j+t];
}
y->n = t - 1;
for (int j = n; j >= i+1; j--)
C[j+1] = C[j];
C[i+1] = z;
for (int j = n-1; j >= i; j--)
keys[j+1] = keys[j];
keys[i] = y->keys[t-1];
n = n + 1;
}

21 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

void BTreeNode::traverse() {
int i;
for (i = 0; i < n; i++) {
if (leaf == false)
C[i]->traverse();
cout << " " << keys[i];
}
if (leaf == false) C[i]->traverse();
}
BTreeNode *BTreeNode::search(int k) {
int i = 0;
while (i < n && k > keys[i])
i++;
if (keys[i] == k) return this;
if (leaf == true) return NULL;
return C[i]->search(k);
}
void BTree::remove(int k) {
if (!root) { cout << "The tree is empty\n"; return; }
root->remove(k);
if (root->n==0) {
BTreeNode *tmp = root;
if (root->leaf)
root = NULL;
else
root = root->C[0];
delete tmp;
}
return;
}

22 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

int main()
{
BTree t(3);
t.insert(1); t.insert(3); t.insert(7); t.insert(10);
t.insert(11); t.insert(13); t.insert(14); t.insert(15);
t.insert(18); t.insert(16); t.insert(19); t.insert(24);
t.insert(25); t.insert(26); t.insert(21); t.insert(4);
t.insert(5); t.insert(20); t.insert(22); t.insert(2);
t.insert(17); t.insert(12); t.insert(6);
cout << "Traversal of tree constructed is\n";
t.traverse(); cout << endl; t.remove(6);
cout << "Traversal of tree after removing 6\n";
t.traverse(); cout << endl; t.remove(13);
cout << "Traversal of tree after removing 13\n";
t.traverse(); cout << endl; t.remove(7);
cout << "Traversal of tree after removing 7\n";
t.traverse(); cout << endl; t.remove(4);
cout << "Traversal of tree after removing 4\n";
t.traverse(); cout << endl; t.remove(2);
cout << "Traversal of tree after removing 2\n";
t.traverse(); cout << endl; t.remove(16);
cout << "Traversal of tree after removing 16\n";
t.traverse(); cout << endl;
return 0;
}

23 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

Output:
Traversal of tree constructed is
1 2 3 4 5 6 7 10 11 12 13 14 15 16 17 18 19 20 21 22 24 25 26
Traversal of tree after removing 6
1 2 3 4 5 7 10 11 12 13 14 15 16 17 18 19 20 21 22 24 25 26
Traversal of tree after removing 13
1 2 3 4 5 7 10 11 12 14 15 16 17 18 19 20 21 22 24 25 26
Traversal of tree after removing 7
1 2 3 4 5 10 11 12 14 15 16 17 18 19 20 21 22 24 25 26
Traversal of tree after removing 4
1 2 3 5 10 11 12 14 15 16 17 18 19 20 21 22 24 25 26
Traversal of tree after removing 2
1 3 5 10 11 12 14 15 16 17 18 19 20 21 22 24 25 26
Traversal of tree after removing 16
1 3 5 10 11 12 14 15 17 18 19 20 21 22 24 25 26

24 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program – 4 C++ Program to implement Min-Max Heap


(Binary Heap) */
#include<iostream>
#include<climits>
using namespace std;
void swap(int *x, int *y);

class MinHeap {
int *harr;
int capacity;
int heap_size;
public:
MinHeap(int capacity);
void MinHeapify(int );
int parent(int i)
{ return (i-1)/2; }
int left(int i)
{ return (2*i + 1); }
int right(int i)
{ return (2*i + 2); }
int extractMin();
void decreaseKey(int i, int new_val);
int getMin()
{ return harr[0]; }
void deleteKey(int i);
void insertKey(int k);
};
MinHeap::MinHeap(int cap) {
heap_size = 0; capacity = cap; harr = new int[cap];
}

25 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

void MinHeap::insertKey(int k) {
if (heap_size == capacity) {
cout << "\nOverflow: Could not insertKey\n"; return;
}
heap_size++;
int i = heap_size - 1; harr[i] = k;
while (i != 0 && harr[parent(i)] > harr[i]) {
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
void MinHeap::decreaseKey(int i, int new_val){
harr[i] = new_val;
while (i != 0 && harr[parent(i)] > harr[i]) {
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
int MinHeap::extractMin()
{
if (heap_size <= 0) return INT_MAX;
if (heap_size == 1) {
heap_size--; return harr[0];
}
int root = harr[0];
harr[0] = harr[heap_size-1];
heap_size--;
MinHeapify(0);
return root;
}

26 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

void MinHeap::deleteKey(int i) {
decreaseKey(i, INT_MIN); extractMin();
}
void MinHeap::MinHeapify(int i) {
int l = left(i); int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i])
smallest = l;
if (r < heap_size && harr[r] < harr[smallest])
smallest = r;
if (smallest != i) {
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
}
}
void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; }
int main()
{
MinHeap h(11);
h.insertKey(3); h.insertKey(2); h.deleteKey(1);
h.insertKey(15); h.insertKey(5);
h.insertKey(4); h.insertKey(45);
cout << h.extractMin() << " ";
cout << h.getMin() << " ";
h.decreaseKey(2, 1);
cout << h.getMin();
return 0;
}
Output:
2 4 1

27 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program – 5 Program to implement Leftist Tree */


#include <iostream>
#include <cstdlib>
class LeftistNode {
public:
int element;
LeftistNode *left;
LeftistNode *right;
int dist;
LeftistNode(int & element, LeftistNode *lt = NULL,
LeftistNode *rt = NULL, int np = 0)
{
this->element = element;
right = rt; left = lt; dist = np;
}
};
class LeftistHeap {
public:
LeftistHeap();
LeftistHeap(LeftistHeap &rhs);
~LeftistHeap();
bool isEmpty();
bool isFull();
int &findMin();
void Insert(int &x);
void deleteMin();
void deleteMin(int &minItem);
void makeEmpty();
void Merge(LeftistHeap &rhs);
LeftistHeap & operator =(LeftistHeap &rhs);

28 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

private:
LeftistNode *root;
LeftistNode *Merge(LeftistNode *h1, LeftistNode *h2);
LeftistNode *Merge1(LeftistNode *h1, LeftistNode *h2);
void swapChildren(LeftistNode * t);
void reclaimMemory(LeftistNode * t);
LeftistNode *clone(LeftistNode *t);
};
LeftistHeap::LeftistHeap() { root = NULL; }
LeftistHeap::LeftistHeap(LeftistHeap &rhs) {
root = NULL;
*this = rhs;
}
LeftistHeap::~LeftistHeap() { makeEmpty( ); }
void LeftistHeap::Merge(LeftistHeap &rhs) {
if (this == &rhs) return;
root = Merge(root, rhs.root);
rhs.root = NULL;
}
LeftistNode *LeftistHeap::Merge(LeftistNode * h1,LeftistNode * h2){
if (h1 == NULL) return h2;
if (h2 == NULL) return h1;
if (h1->element < h2->element)
return Merge1(h1, h2);
else
return Merge1(h2, h1);
}

29 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

LeftistNode *LeftistHeap::Merge1(LeftistNode *h1,LeftistNode *h2){


if (h1->left == NULL)
h1->left = h2;
else {
h1->right = Merge(h1->right, h2);
if (h1->left->dist < h1->right->dist)
swapChildren(h1);
h1->dist = h1->right->dist + 1;
}
return h1;
}
void LeftistHeap::swapChildren(LeftistNode * t) {
LeftistNode *tmp = t->left;
t->left = t->right;
t->right = tmp;
}
void LeftistHeap::Insert(int &x) {
root = Merge(new LeftistNode(x), root);
}
int &LeftistHeap::findMin()
{ return root->element; }
void LeftistHeap::deleteMin() {
LeftistNode *oldRoot = root;
root = Merge(root->left, root->right);
delete oldRoot;
}
void LeftistHeap::deleteMin(int &minItem) {
if (isEmpty()) cout<<"Heap is Empty"<<endl; return;
minItem = findMin(); deleteMin();
}

30 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

bool LeftistHeap::isEmpty()
{ return root == NULL; }
bool LeftistHeap::isFull()
{ return false; }
void LeftistHeap::makeEmpty() {
reclaimMemory(root); root = NULL;
}
LeftistHeap &LeftistHeap::operator =(LeftistHeap & rhs){
if (this != &rhs) {
makeEmpty(); root = clone(rhs.root);
}
return *this;
}
void LeftistHeap::reclaimMemory(LeftistNode * t) {
if (t != NULL) {
reclaimMemory(t->left); reclaimMemory(t->right);
delete t;
}
}
LeftistNode *LeftistHeap::clone(LeftistNode * t) {
if (t == NULL) return NULL;
else
return new LeftistNode(t->element, clone(t->left),
clone(t->right), t->dist);
}
int main(){
LeftistHeap h;
LeftistHeap h1;
LeftistHeap h2;
int x;

31 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

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

32 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program – 6 C++ Program to implement Binomial Heap */


#include <bits/stdc++.h>
using namespace std;
struct Node {
int val, degree;
Node *parent, *child, *sibling;
};
Node *root = NULL;
int binomialLink(Node *h1, Node *h2) {
h1->parent = h2;
h1->sibling = h2->child;
h2->child = h1;
h2->degree = h2->degree + 1;
}
Node *createNode(int n) {
Node *new_node = new Node;
new_node->val = n;
new_node->parent = NULL;
new_node->sibling = NULL;
new_node->child = NULL;
new_node->degree = 0;
return new_node;
}
Node *mergeBHeaps(Node *h1, Node *h2) {
if (h1 == NULL) return h2;
if (h2 == NULL) return h1;
Node *res = NULL;
if (h1->degree <= h2->degree)
res = h1;

33 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

else if (h1->degree > h2->degree)


res = h2;
while (h1 != NULL && h2 != NULL) {
if (h1->degree < h2->degree)
h1 = h1->sibling;
else if (h1->degree == h2->degree){
Node *sib = h1->sibling;
h1->sibling = h2; h1 = sib;
}
else {
Node *sib = h2->sibling;
h2->sibling = h1;
h2 = sib;
}
}
return res;
}
Node *unionBHeaps(Node *h1, Node *h2) {
if (h1 == NULL && h2 == NULL) return NULL;
Node *res = mergeBHeaps(h1, h2);
Node *prev = NULL, *curr = res,
*next = curr->sibling;
while (next != NULL) {
if ((curr->degree != next->degree) ||
((next->sibling != NULL) &&
(next->sibling)->degree == curr->degree))
{
prev = curr; curr = next;
}
else {

34 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

if (curr->val <= next->val) {


curr->sibling = next->sibling;
binomialLink(next, curr);
}
else {
if (prev == NULL) res = next;
else
prev->sibling = next;
binomialLink(curr, next);
curr = next;
}
} next = curr->sibling;
} return res;
}
void binomialHeapInsert(int x)
{
root = unionBHeaps(root, createNode(x));
}
void display(Node *h) {
while (h) {
cout << h->val << " "; display(h->child); h = h->sibling;
}
}
int revertList(Node *h) {
if (h->sibling != NULL) {
revertList(h->sibling); (h->sibling)->sibling = h;
}
else
root = h;
}

35 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

Node *extractMinBHeap(Node *h) {


if (h == NULL) return NULL; Node *min_node_prev = NULL;
Node *min_node = h; int min = h->val;
Node *curr = h;
while (curr->sibling != NULL) {
if ((curr->sibling)->val < min) {
min = (curr->sibling)->val; min_node_prev = curr;
min_node = curr->sibling;
} curr = curr->sibling;
}
if (min_node_prev == NULL && min_node->sibling == NULL)
h = NULL;
else if (min_node_prev == NULL)
h = min_node->sibling;
else
min_node_prev->sibling = min_node->sibling;
if (min_node->child != NULL) {
revertList(min_node->child);
(min_node->child)->sibling = NULL;
}
return unionBHeaps(h, root);
}
Node *findNode(Node *h, int val) {
if (h == NULL) return NULL;
if (h->val == val) return h;
Node *res = findNode(h->child, val);
if (res != NULL) return res;
return findNode(h->sibling, val);
}

36 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

void decreaseKeyBHeap(Node *H, int old_val, int new_val) {


Node *node = findNode(H, old_val);
if (node == NULL) return;
node->val = new_val;
Node *parent = node->parent;
while (parent != NULL && node->val < parent->val) {
swap(node->val, parent->val); node = parent;
parent = parent->parent;
}
}
Node *binomialHeapDelete(Node *h, int val) {
if (h == NULL) return NULL;
decreaseKeyBHeap(h, val, INT_MIN);
return extractMinBHeap(h);
}
int main() {
binomialHeapInsert(10); binomialHeapInsert(20);
binomialHeapInsert(30); binomialHeapInsert(40);
binomialHeapInsert(50);
cout << "The heap is:\n"; display(root);
root = binomialHeapDelete(root, 10);
cout << "\nAfter deleing 10, the heap is:\n"; display(root);
return 0;
}

Output:
The heap is:
50 10 30 40 20
After deleing 10, the heap is:
20 30 40 50

37 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program – 7 C++ Program to implement AVL Tree */


#include <iostream.h>
#include <stdlib.h>
#include<constream.h>
#define FALSE 0
#define TRUE 1
struct AVLNode
{
int data ;
int balfact ;
AVLNode *left ;
AVLNode *right ;
};
class avltree
{
private :
AVLNode *root ;
public :
avltree( ) ;
AVLNode* insert ( int data, int *h ) ;
static AVLNode* buildtree (AVLNode *root, int data, int *h);
void display( AVLNode *root ) ;
AVLNode* deldata (AVLNode* root, int data, int *h);
static AVLNode* del ( AVLNode *node, AVLNode* root, int *h );
static AVLNode* balright ( AVLNode *root, int *h );
static AVLNode* balleft ( AVLNode* root, int *h ) ;
void setroot ( AVLNode *avl ) ;
~avltree( ) ;
static void deltree ( AVLNode *root ) ;
} ;
avltree :: avltree( )
{ root = NULL ; }

AVLNode* avltree :: insert ( int data, int *h )


{
root = buildtree (root, data, h); return root ; }

AVLNode* avltree :: buildtree(AVLNode *root, int data, int *h)


{
AVLNode *node1, *node2 ;
if ( root == NULL )
{
root = new AVLNode ;
root -> data = data ;
root -> left = NULL ; root -> right = NULL ;
root -> balfact = 0 ;
*h = TRUE ;
return ( root ) ;
}

38 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

if ( data < root -> data ) {


root -> left = buildtree ( root -> left, data, h );
if ( *h ) {
switch ( root -> balfact ) {
case 1 :
node1 = root -> left;
if ( node1 -> balfact == 1 ) {
cout << "\nRight rotation." ;
root -> left = node1 -> right ;
node1 -> right = root;
root -> balfact = 0;
root = node1;
}
else {
cout << "\nDouble rotation,left then
right.";
node2 = node1 -> right;
node1 -> right = node2 -> left;
node2 -> left = node1;
root -> left = node2 -> right;
node2 -> right = root;
if ( node2 -> balfact == 1 )
root -> balfact = -1;
else
root -> balfact = 0;
if ( node2 -> balfact == -1 )
node1 -> balfact = 1;
else
node1 -> balfact = 0;
root = node2;
}
root -> balfact = 0;
*h = FALSE; break;
case 0 :
root -> balfact = 1; break;
case -1 :
root -> balfact = 0; *h = FALSE;
}
}
}
if ( data > root -> data )
{
root -> right = buildtree ( root->right, data, h);
if ( *h )
{
switch ( root -> balfact )
{
case 1 :
root -> balfact = 0 ;
*h = FALSE ; break ;

39 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

case 0 :
root -> balfact = -1 ;
break ;
case -1 :
node1 = root -> right ;
if ( node1 -> balfact == -1 )
{
cout << "\nLeft rotation." ;
root -> right = node1 -> left ;
node1 -> left = root ;
root -> balfact = 0 ;
root = node1 ;
}
else
{
cout << "\nDouble rotation, right then
left." ;
node2 = node1 -> left;
node1-> left = node2 -> right;
node2-> right = node1;
root -> right = node2 -> left ;
node2 -> left = root ;
if ( node2 -> balfact == -1 )
root -> balfact = 1 ;
else
root -> balfact = 0 ;
if ( node2 -> balfact == 1 )
node1 -> balfact = -1 ;
else
node1 -> balfact = 0 ;
root = node2 ;
}
root -> balfact = 0 ;
*h = FALSE ;
}
}
}
return ( root ) ;
}
void avltree :: display ( AVLNode* root ){
if ( root != NULL ){
display ( root -> left ) ; cout << root -> data << "\t" ;
display ( root -> right ) ;
}
}
AVLNode* avltree :: deldata (AVLNode *root,int data,int *h )
{
AVLNode *node ;
if ( root -> data == 13 )
cout << root -> data ;

40 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

if ( root == NULL ){
cout << "\nNo such data." ;
return ( root ) ;
}
else {
if ( data < root -> data ){
root->left = deldata(root->left, data, h);
if ( *h )
root = balright ( root, h ) ;
}
else {
if ( data > root -> data ) {
root->right=deldata(root->right,data,h);
if ( *h )
root = balleft ( root, h ) ;
}
else {
node = root ;
if ( node -> right == NULL ) {
root = node -> left ;
*h = TRUE ; delete ( node ) ;
}
else {
if ( node -> left == NULL ) {
root = node -> right ;
*h = TRUE ; delete ( node ) ;
}
else {
node->right=del(node->right,node,h);
if ( *h )
root = balleft(root, h);
}
}
}
}
}
return ( root ) ;
}
AVLNode* avltree :: del (AVLNode *succ,AVLNode *node, int *h) {
AVLNode *temp = succ ;
if ( succ -> left != NULL ) {
succ -> left = del ( succ -> left, node, h ) ;
if ( *h ) succ = balright ( succ, h ) ;
}
else {
temp = succ ; node -> data = succ -> data ;
succ = succ -> right ; delete ( temp ) ; *h = TRUE ;
}
return ( succ ) ;
}

41 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

AVLNode* avltree :: balright ( AVLNode *root, int *h ){


AVLNode *temp1, *temp2 ;
switch ( root -> balfact ) {
case 1 :
root -> balfact = 0 ;
break ;
case 0 :
root -> balfact = -1 ;
*h = FALSE ;
break ;
case -1 :
temp1 = root -> right ;
if ( temp1 -> balfact <= 0 )
{
cout << "\nLeft rotation." ;
root -> right = temp1 -> left ;
temp1 -> left = root ;
if ( temp1 -> balfact == 0 )
{
root -> balfact = -1 ;
temp1 -> balfact = 1 ;
*h = FALSE ;
}
else
{
root -> balfact = temp1 -> balfact = 0 ;
}
root = temp1 ;
}
else {
cout<<"\nDouble rotation, right then left." ;
temp2 = temp1 -> left ;
temp1 -> left = temp2 -> right ;
temp2 -> right = temp1 ;
root -> right = temp2 -> left ;
temp2 -> left = root ;
if ( temp2 -> balfact == -1 )
root -> balfact = 1 ;
else
root -> balfact = 0 ;
if ( temp2 -> balfact == 1 )
temp1 -> balfact = -1 ;
else
temp1 -> balfact = 0 ;
root = temp2 ;
temp2 -> balfact = 0 ;
}
}
return ( root ) ;
}

42 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

AVLNode* avltree :: balleft ( AVLNode *root, int *h )


{
AVLNode *temp1, *temp2 ;
switch ( root -> balfact )
{
case -1 :
root -> balfact = 0 ; break ;
case 0 :
root -> balfact = 1 ;
*h = FALSE ; break ;
case 1 :
temp1 = root -> left ;
if ( temp1 -> balfact >= 0 ){
cout << "\nRight rotation." ;
root -> left = temp1 -> right ;
temp1 -> right = root ;

if ( temp1 -> balfact == 0 )


{
root -> balfact = 1 ;
temp1 -> balfact = -1 ;
*h = FALSE ;
}
else
{
root -> balfact = temp1 -> balfact = 0 ;
}
root = temp1 ;
}
else {
cout<<"\nDouble rotation, left then right." ;
temp2 = temp1 -> right ;
temp1 -> right = temp2 -> left ;
temp2 -> left = temp1 ;
root -> left = temp2 -> right ;
temp2 -> right = root ;
if ( temp2 -> balfact == 1 )
root -> balfact = -1 ;
else
root -> balfact = 0 ;
if ( temp2-> balfact == -1 )
temp1 -> balfact = 1 ;
else
temp1 -> balfact = 0 ;
root = temp2 ;
temp2 -> balfact = 0 ;
}
}
return ( root ) ;
}

43 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

void avltree :: setroot ( AVLNode *avl )


{
root = avl ;
}

avltree :: ~avltree( )
{
deltree ( root ) ;
}
void avltree :: deltree ( AVLNode *root )
{
if ( root != NULL )
{
deltree ( root -> left ) ;
deltree ( root -> right ) ;
}
delete ( root ) ;
}

void main( )
{
avltree at ;
AVLNode *avl = NULL ;
int h ;
clrscr();

avl = at.insert ( 20, &h ) ;


at.setroot ( avl ) ;

avl = at.insert ( 6, &h ) ;


at.setroot ( avl ) ;

avl = at.insert ( 29, &h ) ;


at.setroot ( avl ) ;

avl = at.insert ( 5, &h ) ;


at.setroot ( avl ) ;

avl = at.insert ( 12, &h ) ;


at.setroot ( avl ) ;

avl = at.insert ( 25, &h ) ;


at.setroot ( avl ) ;

avl = at.insert ( 32, &h ) ;


at.setroot ( avl ) ;

avl = at.insert ( 10, &h ) ;


at.setroot ( avl ) ;

44 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

avl = at.insert ( 15, &h ) ;


at.setroot ( avl ) ;

avl = at.insert ( 27, &h ) ;


at.setroot ( avl ) ;

avl = at.insert ( 13, &h ) ;


at.setroot ( avl ) ;

cout << endl << "AVL tree:\n" ;


at.display ( avl ) ;

avl = at.deldata ( avl, 20, &h ) ;


at.setroot ( avl ) ;

avl = at.deldata ( avl, 12, &h ) ;


at.setroot ( avl ) ;

cout << endl << "AVL tree after deletion of a node:\n" ;


at.display ( avl ) ;
getch();
}

45 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program -8 Implementation of Red-Black Tree */


#include <iostream>
#include <queue>
using namespace std;
enum COLOR { RED, BLACK };
class Node {
public:
int val; COLOR color;
Node *left, *right, *parent;
Node(int val) : val(val) {
parent = left = right = NULL;
color = RED;
}
Node *uncle() {
if (parent == NULL or parent->parent == NULL)
return NULL;
if (parent->isOnLeft()) return parent->parent->right;
else return parent->parent->left;
}
bool isOnLeft() { return this == parent->left; }
Node *sibling() {
if (parent == NULL) return NULL;
if (isOnLeft()) return parent->right;
return parent->left;
}
void moveDown(Node *nParent) {
if (parent != NULL) {
if (isOnLeft()) {
parent->left = nParent;
}

46 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

else {
parent->right = nParent;
}
}
nParent->parent = parent;
parent = nParent;
}

bool hasRedChild() {
return (left != NULL and left->color == RED) or
(right != NULL and right->color == RED);
}
};
class RBTree {
Node *root;
void 7(Node *x) {
Node *nParent = x->right;
if (x == root)
root = nParent;
x->moveDown(nParent);
x->right = nParent->left;
if (nParent->left != NULL)
nParent->left->parent = x;
nParent->left = x;
}
void rightRotate(Node *x) {
Node *nParent = x->left;
if (x == root)
root = nParent;
x->moveDown(nParent);

47 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

x->left = nParent->right;
if (nParent->right != NULL)
nParent->right->parent = x;
nParent->right = x;
}
void swapColors(Node *x1, Node *x2) {
COLOR temp;
temp = x1->color;
x1->color = x2->color;
x2->color = temp;
}
void swapValues(Node *u, Node *v) {
int temp;
temp = u->val;
u->val = v->val;
v->val = temp;
}
void fixRedRed(Node *x) {
if (x == root) {
x->color = BLACK;
return;
}
Node *parent = x->parent, *grandparent = parent->parent,
*uncle = x->uncle();
if (parent->color != BLACK) {
if (uncle != NULL && uncle->color == RED) {
parent->color = BLACK;
uncle->color = BLACK;
grandparent->color = RED;
fixRedRed(grandparent);

48 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

} else {
if (parent->isOnLeft()) {
if (x->isOnLeft()) {
swapColors(parent, grandparent);
} else {
leftRotate(parent);
swapColors(x, grandparent);
}
rightRotate(grandparent);
} else {
if (x->isOnLeft()) {
rightRotate(parent);
swapColors(x, grandparent);
} else {
swapColors(parent, grandparent);
}
leftRotate(grandparent);
}
}
}
}
Node *successor(Node *x) {
Node *temp = x;
while (temp->left != NULL)
temp = temp->left;
return temp;
}
Node *BSTreplace(Node *x) {
if (x->left != NULL and x->right != NULL)
return successor(x->right);

49 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

if (x->left == NULL and x->right == NULL)


return NULL;
if (x->left != NULL)
return x->left;
else
return x->right;
}
void deleteNode(Node *v) {
Node *u = BSTreplace(v);
bool uvBlack=((u==NULL or u->color==BLACK)
and (v->color==BLACK));
Node *parent = v->parent;
if (u == NULL) {
if (v == root) {
root = NULL;
} else {
if (uvBlack) {
fixDoubleBlack(v);
} else {
if (v->sibling() != NULL)
v->sibling()->color = RED;
}
if (v->isOnLeft()) {
parent->left = NULL;
} else {
parent->right = NULL;
}
}
delete v; return;
}

50 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

if (v->left == NULL or v->right == NULL) {


if (v == root) {
v->val = u->val;
v->left = v->right = NULL;
delete u;
} else {
if (v->isOnLeft()) {
parent->left = u;
} else {
parent->right = u;
}
delete v;
u->parent = parent;
if (uvBlack) {
fixDoubleBlack(u);
} else {
u->color = BLACK;
}
}
return;
}
swapValues(u, v);
deleteNode(u);
}
void fixDoubleBlack(Node *x) {
if (x == root)
return;
Node *sibling = x->sibling(), *parent = x->parent;
if (sibling == NULL) {
fixDoubleBlack(parent);

51 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

} else {
if (sibling->color == RED) {
parent->color = RED;
sibling->color = BLACK;
if (sibling->isOnLeft()) {
rightRotate(parent);
} else {
leftRotate(parent);
}
fixDoubleBlack(x);
} else {
if (sibling->hasRedChild()) {
if (sibling->left != NULL and sibling->left->color==RED)
{
if (sibling->isOnLeft()) {
sibling->left->color = sibling->color;
sibling->color = parent->color;
rightRotate(parent);
} else {
sibling->left->color = parent->color;
rightRotate(sibling);
leftRotate(parent);
}
} else {
if (sibling->isOnLeft()) {
sibling->right->color = parent->color;
leftRotate(sibling);
rightRotate(parent);
} else {
sibling->right->color = sibling->color;

52 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

sibling->color = parent->color;
leftRotate(parent);
}
}
parent->color = BLACK;
} else {
sibling->color = RED;
if (parent->color == BLACK)
fixDoubleBlack(parent);
else parent->color = BLACK;
}
}
}
}
void levelOrder(Node *x) {
if (x == NULL)
return;
queue<Node *> q;
Node *curr;
q.push(x);
while (!q.empty()) {
// while q is not empty
// dequeue
curr = q.front();
q.pop();

// print node value


cout << curr->val << " ";

// push children to queue

53 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

if (curr->left != NULL)
q.push(curr->left);
if (curr->right != NULL)
q.push(curr->right);
}
}

// prints inorder recursively


void inorder(Node *x) {
if (x == NULL)
return;
inorder(x->left);
cout << x->val << " ";
inorder(x->right);
}

public:
// constructor
// initialize root
RBTree() { root = NULL; }

Node *getRoot() { return root; }

// searches for given value


// if found returns the node (used for delete)
// else returns the last node while traversing (used in insert)
Node *search(int n) {
Node *temp = root;
while (temp != NULL) {
if (n < temp->val) {

54 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

if (temp->left == NULL)
break;
else
temp = temp->left;
} else if (n == temp->val) {
break;
} else {
if (temp->right == NULL)
break;
else
temp = temp->right;
}
}

return temp;
}

// inserts the given value to tree


void insert(int n) {
Node *newNode = new Node(n);
if (root == NULL) {
// when root is null
// simply insert value at root
newNode->color = BLACK;
root = newNode;
} else {
Node *temp = search(n);

if (temp->val == n) {
// return if value already exists

55 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

return;
}

// if value is not found, search returns the node


// where the value is to be inserted

// connect new node to correct node


newNode->parent = temp;

if (n < temp->val)
temp->left = newNode;
else
temp->right = newNode;

// fix red red voilaton if exists


fixRedRed(newNode);
}
}

// utility function that deletes the node with given value


void deleteByVal(int n) {
if (root == NULL)
// Tree is empty
return;

Node *v = search(n), *u;

if (v->val != n) {
cout << "No node found to delete with value:" << n << endl;
return;

56 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

deleteNode(v);
}

// prints inorder of the tree


void printInOrder() {
cout << "Inorder: " << endl;
if (root == NULL)
cout << "Tree is empty" << endl;
else
inorder(root);
cout << endl;
}

// prints level order of the tree


void printLevelOrder() {
cout << "Level order: " << endl;
if (root == NULL)
cout << "Tree is empty" << endl;
else
levelOrder(root);
cout << endl;
}
};

int main() {
RBTree tree;

tree.insert(7);

57 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

tree.insert(3); tree.insert(18); tree.insert(10);


tree.insert(22); tree.insert(8); tree.insert(11);
tree.insert(26); tree.insert(2); tree.insert(6);
tree.insert(13); tree.printInOrder(); tree.printLevelOrder();

cout<<endl<<"Deleting 18, 11, 3, 10, 22"<<endl;

tree.deleteByVal(18); tree.deleteByVal(11);
tree.deleteByVal(3); tree.deleteByVal(10);
tree.deleteByVal(22);
tree.printInOrder();
tree.printLevelOrder();
return 0;
}

58 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

Output:
Inorder:
2 3 6 7 8 10 11 13 18 22 26
Level order:
10 7 18 3 8 11 22 2 6 13 26

Deleting 18, 11, 3, 10, 22


Inorder:
2 6 7 8 13 26
Level order:
13 7 26 6 8 2

59 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program – 9 C++ Program to Implement All Functions of


Dictionary(ADT) Using Hashing */

#include <iostream>
using namespace std;
const int MAX=10;

class dictionary;
class node
{
string key,value;
node *next;
public:
friend class dictionary;
node()
{ next=NULL; }
node(string key,string value)
{
this->key=key;
this->value=value;
next=NULL;
}
};

class dictionary
{
node *head[MAX];
public:
dictionary(){
for(int i=0;i<MAX;i++)
head[i]=NULL;

60 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

}
int hashf(string word);
void insert(string,string);
void find(string word);
bool deleteWord(string word);
void display();
};

int dictionary::hashf(string word)


{
int asciiSum=0;
for(int i=0;i<word.length();i++)
{
asciiSum=asciiSum+word[i];
}
return (asciiSum%10);
}

void dictionary::find(string word)


{
int index=hashf(word);
int flag=0;
node *start=head[index];
while(start!=NULL)
{

if(start->key==word)
{
flag=1;
break;
}

61 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

start=start->next;
}
if(flag==1)
cout<<"Word Is present.";
else
cout<<"Word Is not present.";
}

void dictionary::insert(string word,string meaning)


{
int index=hashf(word);
node *p=new node(word,meaning);

if(head[index]==NULL)
{
head[index]=p;
}
else
{
node *start=head[index];
while(start->next!=NULL)
start=start->next;

start->next=p;
}

cout<<endl<<word<<" inserted into dictionary at


index"<<index;
}

bool dictionary::deleteWord(string word)

62 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

{
int index=hashf(word);
node *tmp=head[index];
node *par=head[index];
if(tmp==NULL) //if no word is present at that index
{
return false;
}
if(tmp->key==word && tmp->next==NULL)
//only one word is present
{
head[index]=NULL;
delete tmp;
return true;
}
//tmp=tmp->next;
while(tmp->key!=word && tmp->next!=NULL)
{
par=tmp;
tmp=tmp->next;
}
if(tmp->key==word&&tmp->next!=NULL)
{
if(par->key==tmp->key)
{ head[index]=tmp->next; }
else
{
par->next=tmp->next;
tmp->next=NULL;
}
delete tmp;

63 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

return true;
}
else //delete at end
{
par->next=NULL;
tmp->next=NULL;
delete tmp;
return true;
}
return false;
}

void dictionary:: display()


{
cout<<"\nIndex\t Key\t Value";
for(int i=0;i<10;i++)
{
node *start=head[i];
if(start==NULL)
cout<<"\n";
while(start!=NULL)
{
cout<<"\n:"<<i<<"\t"<<start->key <<"\t "<<start-
>value;
start=start->next;
}
}
}

int main() {
dictionary oxford;

64 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

int choice;
string word,meaning;
do
{
cout<<"\n**** OXFORD DICTIONARY ****\n"
<<"1.Insert Word\n"
<<"2.Find Word\n"
<<"3.Delete Word\n"
<<"4.Display\n"
<<"Enter Your Choice :";
cin>>choice;

switch(choice)
{
case 1:
cout<<"Enter Word: ";
cin>>word;
cout<<"Enter Meaning: ";
cin>>meaning;
oxford.insert(word,meaning); break;
case 2:
cout<<"Enter Word to Search: ";
cin>>word;
oxford.find(word); break;
case 3:
cout<<"Enter Word to Delete: ";
cin>>word;
if(oxford.deleteWord(word))
cout<<" Word is deleted.";

65 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

else
{
cout<<"\nFailed to delete "<<word;
}
break;
case 4:
cout<<"***Oxford Dictionary***";
oxford.display();
break;
default:
cout<<"\nWrong Choice.";
}

}while(choice!=0);

return 0;
}

66 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

OUTPUT:
**** OXFORD DICTIONARY ****
1.Insert Word
2.Find Word
3.Delete Word
4.Display
Enter Your Choice :1
Enter Word: a
Enter Meaning: ant

a inserted into dictionary at index7


**** OXFORD DICTIONARY ****
1.Insert Word
2.Find Word
3.Delete Word
4.Display
Enter Your Choice :1
Enter Word: b
Enter Meaning: bat

b inserted into dictionary at index8


**** OXFORD DICTIONARY ****
1.Insert Word
2.Find Word
3.Delete Word
4.Display
Enter Your Choice :2
Enter Word to Search: b

67 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

Word Is present.
**** OXFORD DICTIONARY ****
1.Insert Word
2.Find Word
3.Delete Word
4.Display
Enter Your Choice :2
Enter Word to Search: c
Word Is not present.
**** OXFORD DICTIONARY ****
1.Insert Word
2.Find Word
3.Delete Word
4.Display
Enter Your Choice :4
***Oxford Dictionary***
Index Key Value

:7 a ant
:8 b bat

**** OXFORD DICTIONARY ****

68 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

1.Insert Word
2.Find Word
3.Delete Word
4.Display
Enter Your Choice :3
Enter Word to Delete: c

Failed to delete c
**** OXFORD DICTIONARY ****
1.Insert Word
2.Find Word
3.Delete Word
4.Display
Enter Your Choice :3
Enter Word to Delete: b
Word is deleted.
**** OXFORD DICTIONARY ****
1.Insert Word
2.Find Word
3.Delete Word
4.Display
Enter Your Choice :

69 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program – 10 Program to implement Knuth Morris Pratt Pattern


Searching Algorithm */
#include <bits/stdc++.h>
void computeLPSArray(char* pat, int M, int* lps);

void KMPSearch(char* pat, char* txt) {


int M = strlen(pat);
int N = strlen(txt);
int lps[M];

computeLPSArray(pat, M, lps);
int i = 0; int j = 0;
while (i < N) {
if (pat[j] == txt[i]) {
j++; i++;
}
if (j == M) {
printf("Found pattern at index %d ", i - j);
j = lps[j - 1];
}
else if (i < N && pat[j] != txt[i]) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}

70 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

void computeLPSArray(char* pat, int M, int* lps) {


int len = 0; lps[0] = 0;
int i = 1;
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
}
else
{
if (len != 0) { len = lps[len - 1]; }
else
{ lps[i] = 0; i++; }
}
}
}

int main() {
char txt[] = "ABABDABACDABABCABAB";
char pat[] = "ABABCABAB";
KMPSearch(pat, txt); return 0;
}
Output:

Found pattern at index 10

71 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program – 11 Program to implement Brute Force Pattern Matching


Algorithm */
#include <stdio.h>
#include <string.h>
void searchPatter_novice(char *str, char *p) {
int pLen = strlen(p); int strLen = strlen(str);
int Limit, i, j;
Limit = strLen - pLen;
for (i = 0; i <= Limit; i++) {
for (j = 0; j < pLen; j++) {
if(p[j] != str[i+j]) { break; }
}
if(j == pLen) { printf("Pattern found at position %d\n", i); }
}
}
int main(void) {
char str[] = "AABAAAB"; char p[] = "AA";
searchPatter_novice(str, p);
return 0;
}

Output:
Pattern found at index 0

Pattern found at index 9

Pattern found at index 13

72 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

/* Program – 12 Program to implement Boyer Moore Pattern Matching


Algorithm */

# include <limits.h>
# include <string.h>
# include <stdio.h>
# define NO_OF_CHARS 256
int max (int a, int b) { return (a > b)? a: b; }

void badCharHeuristic( char *str, int size, int badchar[NO_OF_CHARS])


{
int i;
for (i = 0; i < NO_OF_CHARS; i++)
badchar[i] = -1;
for (i = 0; i < size; i++)
badchar[(int) str[i]] = i;
}

void search( char *txt, char *pat) {


int m = strlen(pat); int n = strlen(txt);
int badchar[NO_OF_CHARS];
badCharHeuristic(pat, m, badchar);
int s = 0;
while(s <= (n - m))
{
int j = m-1;
while(j >= 0 && pat[j] == txt[s+j])
j--;

73 | P a g e
M Tech CS (PTPG) Sem – I Advanced Data Structures Lab Record

if (j < 0) {
printf("\n pattern occurs at shift = %d", s);
s += (s+m < n)? m-badchar[txt[s+m]] : 1;
}
else
s += max(1, j - badchar[txt[s+j]]);
}
}
int main()
{
char txt[] = "ABAAABCD";
char pat[] = "ABC";
search(txt, pat);
return 0;
}

Output:
pattern occurs at shift = 4

74 | P a g e

You might also like