0% found this document useful (0 votes)
20 views39 pages

Dsa Lab Manual

Uploaded by

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

Dsa Lab Manual

Uploaded by

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

1

LAB MANUAL
Data Structures and Algorithm
IT-201
B.Tech. 5th Semester

Course Coordinator: Dr. Virender Ranga

Department of Information Technology,


Delhi Technological University
Delhi – 110042, India
Submitted By : Aryan Swaroop (2K22/EC/58)
2

List of Experiments
Page
S.No. Practical Signature
No.
a)WAP to implement Linear search and Binary
search on 1D array of Integers.
1 4
b)WAP to implement Insertion and Selection sort
on 1D array of strings.
(a) WAP to implement Stack ADT using Arrays
which has basic operations as Create(),
IsEmpty(), Push(), Pop(), IsFull() with appropriate
2 prototype to a functions. 7

(b) WAP to evaluate a given postfix expression


using stack ADT.
a)WAP to implement a 3-stacks of size ‘m’ in an
array of size ‘n’ with all the basic
operations such as IsEmpty(i), Push(i), Pop(i),

number (1,2,3), m ≅ n/3. Stacks are not


IsFull(i) where ‘i’ denotes the stack

overlapping each other. Leftmost stack facing


the left direction and other two stacks are facing
3 10
in the right direction.

b)WAP to transform infix expression into


equivalent postfix expression using stack.
Also use the user defined operators, $,#, etc, with
appropiate priorities. Eg. A+(B*C-
D/E$F)G)*H, {,/} > $ > {+,-}.
(a) WAP to implement Queue ADT using Arrays
with the basic functions of Create(),
IsEmpty(), Insert(), Delete() and IsFull() with
4 13
suitable prototype to a functions.

(b) WAP to implement Queue using Stacks.


WAP to construct simple linear linked list using
dynamic memory allocation for the
given elements with the following functions,
(a) Inserting a new node,
(b) Accessing a node (finding the position wrt
header),
5 (c) Removing a node with particular key value, 16
(d) Complete deletion of a linked list, and
(e) Displaying the current list.
(f) Copy the linked list and return the pointer of
the new list.
Implement the above program for the elements as
Strings.
3

(a) WAP to find second last node of the given


linked list.
(b) WAP to concatenate two singly linked list in
6 18
sorted order either ascending or
descending.
(c) WAP to sort singly linked list.
WAP to create a Circular Singly Linked List for
the given elements with the following
functions,
(a) Inserting a node, before the node with key
givenkey,
(b) Inserting a node, after the node with key
givenkey,
7 (c) Accessing a node (finding the position wrt 22
header),
(d) Removing a node with particular key value,
(e) Complete deletion of a list,
(f) Displaying the current list, and
(g) Sorting the list.
Implement the above program for the elements as
Strings.
(a) WAP to build a binary tree for the given
elements (integers) and also give traversal
functions : inorder, preorder, postorder.
(b) WAP to traverse a given binary tree in inorder,
preorder, postorder, converse inorder,
converse preorder, converse postorder fashion.
8 25
(converse - traverse in a reverse
direction)
(c) WAP to transform given tree into a binary
tree.
(d) WAP to represent an arithematic expression in
binary tree format.
(a) WAP to implement priority queues using heaps
(min heap or max heap) with add and
9 delete functions. 31
(b) WAP to perform heap sort on the given list of
elements.
(a) WAP to perform BFS for any given graph.
10 34
(b)WAP to perform DFS for any given graph.
4

Experiment 1

Objective :-

a)WAP to implement Linear search and Binary search on 1D array of Integers.

b)WAP to implement Insertion and Selection sort on 1D array of strings.

Code :-

(a)

#include <iostream>
#include <algorithm>

int linearSearch(int arr[], int n, int key) {


for (int i = 0; i < n; i++) {
if (arr[i] == key)
return i;
}
return -1;
}

int binarySearch(int arr[], int n, int key) {


int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}

int main() {
int n, key;

std::cout << "Enter the number of elements: ";


std::cin >> n;

int arr[n];

std::cout << "Enter the elements of the array: ";


for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}

std::cout << "Enter the element to search: ";


std::cin >> key;

int linearResult = linearSearch(arr, n, key);


if (linearResult != -1)
std::cout << "Linear Search: Element found at index " << linearResult << std::endl;
else
std::cout << "Linear Search: Element not found" << std::endl;

std::sort(arr, arr + n);


5

int binaryResult = binarySearch(arr, n, key);


if (binaryResult != -1)
std::cout << "Binary Search: Element found at index " << binaryResult << std::endl;
else
std::cout << "Binary Search: Element not found" << std::endl;

return 0;
}

(b)
#include <iostream>
#include <string>
#include <vector>

void insertionSort(std::vector<std::string>& arr) {


int n = arr.size();
for (int i = 1; i < n; i++) {
std::string key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

void selectionSort(std::vector<std::string>& arr) {


int n = arr.size();
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex])
minIndex = j;
}
std::swap(arr[i], arr[minIndex]);
}
}

int main() {
int n;
std::cout << "Enter the number of strings: ";
std::cin >> n;
std::vector<std::string> arr(n);
std::cout << "Enter the strings: ";
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}

std::vector<std::string> arrCopy = arr;


insertionSort(arrCopy);
std::cout << "Strings after Insertion Sort: ";
for (const auto& str : arrCopy) {
std::cout << str << " ";
}
std::cout << std::endl;

selectionSort(arr);
std::cout << "Strings after Selection Sort: ";
for (const auto& str : arr) {
std::cout << str << " ";
}
std::cout << std::endl;

return 0;
6

Output :-

(a)

(b)
7

Experiment 2

Objective :-

(a) WAP to implement Stack ADT using Arrays which has basic operations as Create(),
IsEmpty(), Push(), Pop(), IsFull() with appropriate prototype to a functions.

(b) WAP to evaluate a given postfix expression using stack ADT.

Code :-

(a)
#include <iostream>
#define MAX 100

class Stack {
int arr[MAX];
int top;

public:
Stack() { top = -1; }

bool isEmpty() {
return top == -1;
}

bool isFull() {
return top == MAX - 1;
}

void push(int value) {


if (isFull()) {
std::cout << "Stack is full. Cannot push " << value << std::endl;
} else {
arr[++top] = value;
std::cout << value << " pushed to stack" << std::endl;
}
}

int pop() {
if (isEmpty()) {
std::cout << "Stack is empty. Cannot pop" << std::endl;
return -1;
} else {
return arr[top--];
}
}
};

int main() {
Stack stack;
stack.push(10);
stack.push(20);
stack.push(30);
std::cout << "Popped: " << stack.pop() << std::endl;
std::cout << "Popped: " << stack.pop() << std::endl;
}

(b)
#include <iostream>
#include <cctype>
#include <cmath>
#define MAX 100
8

class Stack {
int arr[MAX];
int top;

public:
Stack() { top = -1; }

bool isEmpty() {
return top == -1;
}

bool isFull() {
return top == MAX - 1;
}

void push(int value) {


if (!isFull()) {
arr[++top] = value;
}
}

int pop() {
if (!isEmpty()) {
return arr[top--];
}
return -1;
}
};

int evaluatePostfix(std::string exp) {


Stack stack;
for (char ch : exp) {
if (isdigit(ch)) {
stack.push(ch - '0');
} else {
int val2 = stack.pop();
int val1 = stack.pop();
switch (ch) {
case '+': stack.push(val1 + val2); break;
case '-': stack.push(val1 - val2); break;
case '*': stack.push(val1 * val2); break;
case '/': stack.push(val1 / val2); break;
case '^': stack.push(pow(val1, val2)); break;
}
}
}
return stack.pop();
}

int main() {
std::string exp = "53+82-*";
std::cout << "Postfix Evaluation: " << evaluatePostfix(exp) << std::endl;
return 0;
}

Output :-

(a)
9

(b)
10

Experiment 3

Objective :-

a)WAP to implement a 3-stacks of size ‘m’ in an array of size ‘n’ with all the basic

number (1,2,3), m ≅ n/3. Stacks are not overlapping each other. Leftmost stack facing
operations such as IsEmpty(i), Push(i), Pop(i), IsFull(i) where ‘i’ denotes the stack

the left direction and other two stacks are facing in the right direction.

b)WAP to transform infix expression into equivalent postfix expression using stack.
Also use the user defined operators, $,#, etc, with appropiate priorities. Eg. A+(B*C-
D/E$F)G)*H, {,/} > $ > {+,-}.

Code :-

(a)
#include <iostream>
#define MAX 100

class ThreeStacks {
int arr[MAX];
int top1, top2, top3;
int n;

public:
ThreeStacks(int n) {
this->n = n;
top1 = -1;
top2 = n / 3;
top3 = n - 1;
}

bool isEmpty(int stackNumber) {


if (stackNumber == 1)
return top1 == -1;
else if (stackNumber == 2)
return top2 == n / 3;
else
return top3 == n - 1;
}

bool isFull(int stackNumber) {


if (stackNumber == 1)
return top1 == (n / 3) - 1;
else if (stackNumber == 2)
return top2 == (2 * n / 3) - 1;
else
return top3 == (2 * n / 3);
}

void push(int stackNumber, int value) {


if (isFull(stackNumber)) {
std::cout << "Stack " << stackNumber << " is full.\n";
return;
}
if (stackNumber == 1)
arr[++top1] = value;
else if (stackNumber == 2)
arr[++top2] = value;
else
arr[--top3] = value;
}

int pop(int stackNumber) {


if (isEmpty(stackNumber)) {
11

std::cout << "Stack " << stackNumber << " is empty.\n";


return -1;
}
if (stackNumber == 1)
return arr[top1--];
else if (stackNumber == 2)
return arr[top2--];
else
return arr[top3++];
}
};

int main() {
int n = 15;
ThreeStacks ts(n);

ts.push(1, 10);
ts.push(2, 20);
ts.push(3, 30);

std::cout << "Pop from Stack 1: " << ts.pop(1) << std::endl;
std::cout << "Pop from Stack 2: " << ts.pop(2) << std::endl;
std::cout << "Pop from Stack 3: " << ts.pop(3) << std::endl;

return 0;
}

(b)
#include <iostream>
#include <stack>
#include <string>

using namespace std;

int precedence(char op) {


if (op == '/' || op == '#') return 3;
if (op == '$') return 2;
if (op == '+' || op == '-') return 1;
return 0;
}

bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '$' || c == '#';
}

string infixToPostfix(string infix) {


stack<char> s;
string postfix = "";

for (int i = 0; i < infix.length(); i++) {


char c = infix[i];

if (isalnum(c)) {
postfix += c;
}
else if (c == '(') {
s.push(c);
}
else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop();
}
else if (isOperator(c)) {
while (!s.empty() && precedence(s.top()) >= precedence(c)) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
12

while (!s.empty()) {
postfix += s.top();
s.pop();
}

return postfix;
}

int main() {
string infix;
cout << "Enter infix expression: ";
cin >> infix;
string postfix = infixToPostfix(infix);
cout << "Postfix expression: " << postfix << endl;
return 0;
}

Output :-

(a)

(b)
13

Experiment 4

Objective :-
(a) WAP to implement Queue ADT using Arrays with the basic functions of Create(),
IsEmpty(), Insert(), Delete() and IsFull() with suitable prototype to a functions.
(b) WAP to implement Queue using Stacks.

Code :-

(a)
#include <iostream>
using namespace std;

#define MAX 100

class Queue {
int arr[MAX];
int front, rear;

public:
Queue() {
front = rear = -1;
}

bool isEmpty() {
return front == -1;
}

bool isFull() {
return rear == MAX - 1;
}

void insert(int value) {


if (isFull()) {
cout << "Queue is full. Cannot insert " << value << endl;
return;
}
if (front == -1) front = 0;
arr[++rear] = value;
cout << value << " inserted into queue" << endl;
}

int deleteQueue() {
if (isEmpty()) {
cout << "Queue is empty. Cannot delete" << endl;
return -1;
}
int value = arr[front];
if (front >= rear) front = rear = -1;
else front++;
return value;
}

void display() {
if (isEmpty()) {
cout << "Queue is empty" << endl;
return;
}
for (int i = front; i <= rear; i++)
cout << arr[i] << " ";
cout << endl;
}
};

int main() {
Queue q;
q.insert(10);
14

q.insert(20);
q.insert(30);
q.display();
cout << q.deleteQueue() << " deleted from queue" << endl;
q.display();
return 0;
}

(b)
#include <iostream>
#include <stack>
using namespace std;

class QueueUsingStacks {
stack<int> s1, s2;

public:
void enqueue(int value) {
s1.push(value);
}

int dequeue() {
if (s1.empty() && s2.empty()) {
cout << "Queue is empty. Cannot dequeue" << endl;
return -1;
}
if (s2.empty()) {
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
int value = s2.top();
s2.pop();
return value;
}

bool isEmpty() {
return s1.empty() && s2.empty();
}

void display() {
if (isEmpty()) {
cout << "Queue is empty" << endl;
return;
}
while (!s2.empty()) {
cout << s2.top() << " ";
s2.pop();
}
while (!s1.empty()) {
cout << s1.top() << " ";
}
cout << endl;
}
};

int main() {
QueueUsingStacks q;
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
cout << q.dequeue() << " dequeued from queue" << endl;
q.display();
return 0;
}
15

Output :-

(a)

(b)
16

Experiment 5

Objective :-
WAP to construct simple linear linked list using dynamic memory allocation for the
given elements with the following functions,
(a) Inserting a new node,
(b) Accessing a node (finding the position wrt header),
(c) Removing a node with particular key value,
(d) Complete deletion of a linked list, and
(e) Displaying the current list.
(f) Copy the linked list and return the pointer of the new list.
Implement the above program for the elements as Strings.

Code :-

#include <iostream>
#include <string>

struct Node {
std::string data;
Node* next;
};

class LinkedList {
private:
Node* head;

public:
LinkedList() {
head = nullptr;
}

void insert(const std::string& value) {


Node* newNode = new Node();
newNode->data = value;
newNode->next = head;
head = newNode;
}

Node* access(int position) {


Node* current = head;
int index = 0;
while (current != nullptr && index < position) {
current = current->next;
index++;
}
return current;
}

void remove(const std::string& key) {


Node* current = head;
Node* prev = nullptr;
while (current != nullptr && current->data != key) {
prev = current;
current = current->next;
}
if (current == nullptr) return;
if (prev == nullptr) head = current->next;
else prev->next = current->next;
delete current;
}

void deleteList() {
Node* current = head;
while (current != nullptr) {
Node* temp = current;
17

current = current->next;
delete temp;
}
head = nullptr;
}

void display() {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}

LinkedList* copy() {
LinkedList* newList = new LinkedList();
Node* current = head;
while (current != nullptr) {
newList->insert(current->data);
current = current->next;
}
return newList;
}

~LinkedList() {
deleteList();
}
};

int main() {
LinkedList list;
list.insert("Node1");
list.insert("Node2");
list.insert("Node3");
list.display();

Node* accessedNode = list.access(1);


if (accessedNode != nullptr) {
std::cout << "Accessed node: " << accessedNode->data << std::endl;
} else {
std::cout << "Position out of range." << std::endl;
}

list.remove("Node2");
list.display();

LinkedList* copiedList = list.copy();


copiedList->display();

list.deleteList();
copiedList->display();

delete copiedList;
return 0;
}

Output :-
18

Experiment 6

Objective :-
(a) WAP to find second last node of the given linked list.\

(b) WAP to concatenate two singly linked list in sorted order either ascending or
descending.

(c) WAP to sort singly linked list.

Code :-

(a)
#include <iostream>

struct Node {
int data;
Node* next;
};

Node* findSecondLast(Node* head) {


if (head == nullptr || head->next == nullptr)
return nullptr;

Node* secondLast = head;


while (secondLast->next->next != nullptr)
secondLast = secondLast->next;

return secondLast;
}

int main() {
Node* head = new Node{10, new Node{20, new Node{30, new Node{40, nullptr}}}};

Node* secondLast = findSecondLast(head);


if (secondLast)
std::cout << "Second Last Node: " << secondLast->data << std::endl;
else
std::cout << "List is too short" << std::endl;

return 0;
}

(b)
#include <iostream>

struct Node {
int data;
Node* next;
};

Node* mergeSorted(Node* a, Node* b) {


if (!a) return b;
if (!b) return a;

Node* result = nullptr;


if (a->data <= b->data) {
result = a;
result->next = mergeSorted(a->next, b);
} else {
result = b;
result->next = mergeSorted(a, b->next);
}
return result;
}
19

void append(Node*& head, int data) {


Node* newNode = new Node{data, nullptr};
if (!head) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next)
temp = temp->next;
temp->next = newNode;
}

int main() {
Node* list1 = nullptr;
Node* list2 = nullptr;

append(list1, 10);
append(list1, 30);
append(list1, 50);

append(list2, 20);
append(list2, 40);
append(list2, 60);

Node* mergedList = mergeSorted(list1, list2);


Node* temp = mergedList;
while (temp) {
std::cout << temp->data << " ";
temp = temp->next;
}

return 0;
}

(c)
#include <iostream>

struct Node {
int data;
Node* next;
};

void split(Node* head, Node** front, Node** back) {


Node* fast = head->next;
Node* slow = head;

while (fast) {
fast = fast->next;
if (fast) {
slow = slow->next;
fast = fast->next;
}
}

*front = head;
*back = slow->next;
slow->next = nullptr;
}

Node* merge(Node* a, Node* b) {


if (!a) return b;
if (!b) return a;

Node* result = nullptr;


if (a->data <= b->data) {
result = a;
result->next = merge(a->next, b);
} else {
result = b;
result->next = merge(a, b->next);
}
return result;
20

void mergeSort(Node** head) {


if (!*head || !(*head)->next)
return;

Node* a;
Node* b;
split(*head, &a, &b);

mergeSort(&a);
mergeSort(&b);

*head = merge(a, b);


}

void append(Node*& head, int data) {


Node* newNode = new Node{data, nullptr};
if (!head) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next)
temp = temp->next;
temp->next = newNode;
}

int main() {
Node* head = nullptr;

append(head, 30);
append(head, 10);
append(head, 40);
append(head, 20);

mergeSort(&head);

Node* temp = head;


while (temp) {
std::cout << temp->data << " ";
temp = temp->next;
}

return 0;
}

Output :-

(a)
21

(b)

(c)
22

Experiment 7

Objective :-
WAP to create a Circular Singly Linked List for the given elements with the following
functions,
(a) Inserting a node, before the node with key givenkey,
(b) Inserting a node, after the node with key givenkey,
(c) Accessing a node (finding the position wrt header),
(d) Removing a node with particular key value,
(e) Complete deletion of a list,
(f) Displaying the current list, and
(g) Sorting the list.
Implement the above program for the elements as Strings.
Code :-
#include <iostream>
#include <string>

struct Node {
std::string data;
Node* next;
};

class CircularLinkedList {
public:
Node* head;

CircularLinkedList() {
head = nullptr;
}

void insertBefore(std::string key, std::string newData) {


if (head == nullptr) return;

Node* newNode = new Node();


newNode->data = newData;

if (head->data == key) {
Node* last = head;
while (last->next != head) last = last->next;
newNode->next = head;
last->next = newNode;
head = newNode;
return;
}

Node* current = head;


Node* prev = nullptr;

do {
prev = current;
current = current->next;
if (current->data == key) {
newNode->next = current;
prev->next = newNode;
return;
}
} while (current != head);
}

void insertAfter(std::string key, std::string newData) {


if (head == nullptr) return;

Node* newNode = new Node();


23

newNode->data = newData;

Node* current = head;


do {
if (current->data == key) {
newNode->next = current->next;
current->next = newNode;
return;
}
current = current->next;
} while (current != head);
}

int findPosition(std::string key) {


if (head == nullptr) return -1;

Node* current = head;


int pos = 0;

do {
if (current->data == key) return pos;
current = current->next;
pos++;
} while (current != head);

return -1;
}

void removeNode(std::string key) {


if (head == nullptr) return;

if (head->data == key) {
Node* last = head;
while (last->next != head) last = last->next;

if (head == last) {
delete head;
head = nullptr;
} else {
Node* temp = head;
last->next = head->next;
head = head->next;
delete temp;
}
return;
}

Node* current = head;


Node* prev = nullptr;

do {
prev = current;
current = current->next;
if (current->data == key) {
prev->next = current->next;
delete current;
return;
}
} while (current != head);
}

void deleteList() {
if (head == nullptr) return;

Node* current = head;


Node* nextNode;

do {
nextNode = current->next;
delete current;
current = nextNode;
} while (current != head);

head = nullptr;
24

void display() {
if (head == nullptr) return;

Node* current = head;


do {
std::cout << current->data << " ";
current = current->next;
} while (current != head);
std::cout << std::endl;
}

void sortList() {
if (head == nullptr) return;

Node* current = head;


Node* index = nullptr;
std::string temp;

do {
index = current->next;
while (index != head) {
if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
} while (current->next != head);
}
};

int main() {
CircularLinkedList list;

list.insertAfter("", "apple");
list.insertAfter("apple", "banana");
list.insertAfter("banana", "cherry");
list.display();

list.insertBefore("banana", "apricot");
list.display();

list.insertAfter("banana", "date");
list.display();

std::cout << "Position of 'cherry': " << list.findPosition("cherry") << std::endl;

list.removeNode("banana");
list.display();

list.sortList();
list.display();

list.deleteList();
list.display();

return 0;
}

Output :-
25

Experiment 8

Objective :-
(a) WAP to build a binary tree for the given elements (integers) and also give traversal
functions : inorder, preorder, postorder.
(b) WAP to traverse a given binary tree in inorder, preorder, postorder, converse inorder,
converse preorder, converse postorder fashion. (converse - traverse in a reverse
direction)
(c) WAP to transform given tree into a binary tree.
(d) WAP to represent an arithematic expression in binary tree format.

Code :-
(a)
#include <iostream>

struct Node {
int data;
Node* left;
Node* right;
};

Node* createNode(int data) {


Node* newNode = new Node();
newNode->data = data;
newNode->left = newNode->right = nullptr;
return newNode;
}

Node* insertNode(Node* root, int data) {


if (root == nullptr) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);
} else {
root->right = insertNode(root->right, data);
}
return root;
}

void inorder(Node* root) {


if (root != nullptr) {
inorder(root->left);
std::cout << root->data << " ";
inorder(root->right);
}
}

void preorder(Node* root) {


if (root != nullptr) {
std::cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}
}

void postorder(Node* root) {


if (root != nullptr) {
postorder(root->left);
postorder(root->right);
std::cout << root->data << " ";
}
}
26

int main() {
Node* root = nullptr;
root = insertNode(root, 50);
insertNode(root, 30);
insertNode(root, 20);
insertNode(root, 40);
insertNode(root, 70);
insertNode(root, 60);
insertNode(root, 80);

std::cout << "Inorder Traversal: ";


inorder(root);
std::cout << std::endl;

std::cout << "Preorder Traversal: ";


preorder(root);
std::cout << std::endl;

std::cout << "Postorder Traversal: ";


postorder(root);
std::cout << std::endl;

return 0;
}

(b)
#include <iostream>

struct Node {
int data;
Node* left;
Node* right;
};

Node* createNode(int data) {


Node* newNode = new Node();
newNode->data = data;
newNode->left = newNode->right = nullptr;
return newNode;
}

Node* insertNode(Node* root, int data) {


if (root == nullptr) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);
} else {
root->right = insertNode(root->right, data);
}
return root;
}

void inorder(Node* root) {


if (root != nullptr) {
inorder(root->left);
std::cout << root->data << " ";
inorder(root->right);
}
}

void preorder(Node* root) {


if (root != nullptr) {
std::cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}
}

void postorder(Node* root) {


if (root != nullptr) {
postorder(root->left);
postorder(root->right);
27

std::cout << root->data << " ";


}
}

void converseInorder(Node* root) {


if (root != nullptr) {
converseInorder(root->right);
std::cout << root->data << " ";
converseInorder(root->left);
}
}

void conversePreorder(Node* root) {


if (root != nullptr) {
std::cout << root->data << " ";
conversePreorder(root->right);
conversePreorder(root->left);
}
}

void conversePostorder(Node* root) {


if (root != nullptr) {
conversePostorder(root->right);
conversePostorder(root->left);
std::cout << root->data << " ";
}
}

int main() {
Node* root = nullptr;
root = insertNode(root, 50);
insertNode(root, 30);
insertNode(root, 20);
insertNode(root, 40);
insertNode(root, 70);
insertNode(root, 60);
insertNode(root, 80);

std::cout << "Inorder Traversal: ";


inorder(root);
std::cout << std::endl;

std::cout << "Preorder Traversal: ";


preorder(root);
std::cout << std::endl;

std::cout << "Postorder Traversal: ";


postorder(root);
std::cout << std::endl;

std::cout << "Converse Inorder Traversal: ";


converseInorder(root);
std::cout << std::endl;

std::cout << "Converse Preorder Traversal: ";


conversePreorder(root);
std::cout << std::endl;

std::cout << "Converse Postorder Traversal: ";


conversePostorder(root);
std::cout << std::endl;

return 0;
}

(c)
#include <iostream>
#include <vector>

struct TreeNode {
int data;
std::vector<TreeNode*> children;
TreeNode(int val) : data(val) {}
28

};

struct BinaryTreeNode {
int data;
BinaryTreeNode* left;
BinaryTreeNode* right;
BinaryTreeNode(int val) : data(val), left(nullptr), right(nullptr) {}
};

BinaryTreeNode* transformToBinary(TreeNode* root) {


if (!root) return nullptr;
BinaryTreeNode* binaryRoot = new BinaryTreeNode(root->data);
if (!root->children.empty()) {
binaryRoot->left = transformToBinary(root->children[0]);
BinaryTreeNode* current = binaryRoot->left;
for (size_t i = 1; i < root->children.size(); i++) {
current->right = transformToBinary(root->children[i]);
current = current->right;
}
}
return binaryRoot;
}

void inorderTraversal(BinaryTreeNode* root) {


if (!root) return;
inorderTraversal(root->left);
std::cout << root->data << " ";
inorderTraversal(root->right);
}

int main() {
TreeNode* root = new TreeNode(1);
root->children.push_back(new TreeNode(2));
root->children.push_back(new TreeNode(3));
root->children.push_back(new TreeNode(4));
root->children[0]->children.push_back(new TreeNode(5));
root->children[0]->children.push_back(new TreeNode(6));
root->children[1]->children.push_back(new TreeNode(7));

BinaryTreeNode* binaryTreeRoot = transformToBinary(root);


inorderTraversal(binaryTreeRoot);

return 0;
}

(d)
#include <iostream>
#include <stack>
#include <cctype>

struct Node {
char data;
Node* left;
Node* right;
};

Node* createNode(char data) {


Node* newNode = new Node();
newNode->data = data;
newNode->left = newNode->right = nullptr;
return newNode;
}

bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}

Node* constructExpressionTree(std::string postfix) {


std::stack<Node*> st;
for (int i = 0; i < postfix.length(); i++) {
if (!isOperator(postfix[i])) {
st.push(createNode(postfix[i]));
} else {
29

Node* node = createNode(postfix[i]);


node->right = st.top(); st.pop();
node->left = st.top(); st.pop();
st.push(node);
}
}
return st.top();
}

void inorder(Node* root) {


if (root != nullptr) {
inorder(root->left);
std::cout << root->data << " ";
inorder(root->right);
}
}

int main() {
std::string postfix = "ab+cde+**";
Node* root = constructExpressionTree(postfix);

std::cout << "Inorder Traversal of Expression Tree: ";


inorder(root);
std::cout << std::endl;

return 0;
}

Output :-

(a)

(b)
30

(c)

(d)
31

Experiment 9

Objective :-
(a) WAP to implement priority queues using heaps (min heap or max heap) with add and
delete functions.
(b) WAP to perform heap sort on the given list of elements.

Code :-

(a)
#include <iostream>
#include <vector>

class MinHeap {
private:
std::vector<int> heap;

void heapifyUp(int index) {


if (index == 0) return;
int parent = (index - 1) / 2;
if (heap[parent] > heap[index]) {
std::swap(heap[parent], heap[index]);
heapifyUp(parent);
}
}

void heapifyDown(int index) {


int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
int smallest = index;

if (leftChild < heap.size() && heap[leftChild] < heap[smallest])


smallest = leftChild;
if (rightChild < heap.size() && heap[rightChild] < heap[smallest])
smallest = rightChild;

if (smallest != index) {
std::swap(heap[smallest], heap[index]);
heapifyDown(smallest);
}
}

public:
void add(int value) {
heap.push_back(value);
heapifyUp(heap.size() - 1);
}

int deleteMin() {
if (heap.empty()) return -1;
int minElement = heap[0];
heap[0] = heap.back();
heap.pop_back();
heapifyDown(0);
return minElement;
}

void printHeap() {
for (int i : heap) std::cout << i << " ";
std::cout << std::endl;
}
};

int main() {
MinHeap pq;
pq.add(10);
pq.add(20);
32

pq.add(5);
pq.add(30);
pq.printHeap();
std::cout << "Min element deleted: " << pq.deleteMin() << std::endl;
pq.printHeap();
}

(b)
#include <iostream>
#include <vector>

void heapify(std::vector<int>& arr, int n, int i) {


int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

if (largest != i) {
std::swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}

void heapSort(std::vector<int>& arr, int n) {


for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

for (int i = n - 1; i > 0; i--) {


std::swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}

int main() {
std::vector<int> arr = {12, 11, 13, 5, 6, 7};
int n = arr.size();

heapSort(arr, n);

std::cout << "Sorted array: ";


for (int i : arr)
std::cout << i << " ";
std::cout << std::endl;

return 0;
}
33

Output :-

(a)

(b)
34

Experiment 10

Objective :-
(a) WAP to perform BFS for any given graph.
(b)WAP to perform DFS for any given graph.

Code :-

(a)
#include <iostream>
#include <vector>
#include <queue>

void BFS(int start, std::vector<std::vector<int>>& adj, int n) {


std::vector<bool> visited(n, false);
std::queue<int> q;
q.push(start);
visited[start] = true;

while (!q.empty()) {
int node = q.front();
q.pop();
std::cout << node << " ";

for (int neighbor : adj[node]) {


if (!visited[neighbor]) {
q.push(neighbor);
visited[neighbor] = true;
}
}
}
}

int main() {
int n, edges;
std::cin >> n >> edges;
std::vector<std::vector<int>> adj(n);

for (int i = 0; i < edges; i++) {


int u, v;
std::cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}

int start;
std::cout << "Enter start node for BFS: ";
std::cin >> start;
BFS(start, adj, n);

return 0;
}

(b)
#include <iostream>
#include <vector>

void DFSUtil(int node, std::vector<bool>& visited, std::vector<std::vector<int>>& adj) {


visited[node] = true;
std::cout << node << " ";

for (int neighbor : adj[node]) {


if (!visited[neighbor])
DFSUtil(neighbor, visited, adj);
35

}
}

void DFS(int start, std::vector<std::vector<int>>& adj, int n) {


std::vector<bool> visited(n, false);
DFSUtil(start, visited, adj);
}

int main() {
int n, edges;
std::cin >> n >> edges;
std::vector<std::vector<int>> adj(n);

for (int i = 0; i < edges; i++) {


int u, v;
std::cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}

int start;
std::cout << "Enter start node for DFS: ";
std::cin >> start;
DFS(start, adj, n);

return 0;
}

Output :-

(a)
36

(b)
37

Experiment 11

Objective :-
(a) Wap to implement merge short on 1D Array of integers.
(b) Wap to implement bubble short on 1D Array of integers.

Code :-

(a)

#include <iostream>
using namespace std;

void merge(int arr[], int left, int mid, int right) {


int n1 = mid - left + 1;
int n2 = right - mid;
int leftArr[n1], rightArr[n2];
for (int i = 0; i < n1; i++)
leftArr[i] = arr[left + i];
for (int j = 0; j < n2; j++)
rightArr[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k] = leftArr[i];
i++;
} else {
arr[k] = rightArr[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = leftArr[i];
i++;
k++;
}
while (j < n2) {
arr[k] = rightArr[j];
j++;
k++;
}
}

void mergeSort(int arr[], int left, int right) {


if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}

int main() {
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int arrSize = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
for (int i = 0; i < arrSize; i++)
cout << arr[i] << " ";
cout << endl;
mergeSort(arr, 0, arrSize - 1);
cout << "Sorted array: ";
for (int i = 0; i < arrSize; i++)
cout << arr[i] << " ";
cout << endl;

return 0;
}
38

(b)

#include <iostream>
using namespace std;

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
bubbleSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}

Output :-

(a)
39

(b)

You might also like