Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 57

I.K.

G Punjab Technical University,


Kapurthala
Department of Computer Science Engineering

LAB ASSIGNMENT

Data Structure & Algorithms


BTCS303-18

Bachelor of Technology
(Computer Engineering)

Submitted To: Submitted By:


Dr. Raman kumar Name : Shivam Sharma
Roll no : 2224542
Group : 4th (D2)
1
INDEX

Sr. Tasks Page No. Remarks


No.

Write a program to insert a new element at end a


01 well as at a given position in an array. 5- 6

Write a program to delete an element from a given


02 whose value is given or whose position is given. 6-8

03 Write a program to find the location of a given 8-9


element using Linear Search.

04 Write a program to find the location of a given 9-11


element using Binary Search.

05 Write a program to implement push and pop 11-14


operations on a stack using linear array.

06 Write a program to convert an infix expression to a 14-16


postfix expression using stacks.

2
07 Write a program to evaluate a postfix expression 16-17
using stacks.

08 Write a recursive function for Tower of Hanoi 17-18


problem.

09 Write a program to implement insertion and deletion 19-22


operations in a queue using linear array.

10 Write a menu driven program to perform following 22-30


insertion operations in a single linked list.

11 Write a menu driven program to perform following 30-36


deletion operations in a single linked list.

12 Write a program to implement push and pop 36-39


operations on a stack using linked list.

13 Write a program to implement push and pop 39-42


operations on a queue using linked list.

14 Program to sort an array of integers in ascending 42-43


order using bubble sort.

15 Program to sort an array of integers in ascending 44-45


order using selection sort.

3
16 Program to sort an array of integers in ascending 45-46
order using insertion sort.

17 Program to sort an array of integers in ascending 47-48


order using quick sort.

18 Program to traverse a Binary search tree in In-order, 49-53


Pre-order and Post-order.

19 Program to traverse graphs using BFS. 53-55

20 Program to traverse graphs using DFS. 55-57

TASK-1
Write a program to insert a new element at end as well as at a given
position in an array.
#include <iostream>

4
using namespace std;
int* insertX(int n, int arr[], int x, int pos)
{
int i;
n++;
for (i = n; i >= pos; i--)
arr[i] = arr[i - 1];
arr[pos - 1] = x;

return arr;
}
int main()
{
int arr[100] = { 0 };
int i, x, pos, n = 10;

for (i = 0; i < 10; i++)


arr[i] = i + 1;

for (i = 0; i < n; i++)


cout << arr[i] << " ";

cout << endl;


x = 50;
pos = 5;

insertX(n, arr, x, pos);


for (i = 0; i < n + 1; i++)
cout << arr[i] << " ";

5
cout << endl;
return 0;
}

Output:

TASK-2
Write a program to delete an element from a given whose value is given or
whose position is given.
#include<iostream>
using namespace std;
int main()
{
int i,a[50],no,pos,size;
cout<<"Enter array size( Max:50 ) :: ";
cin>>size;
cout<<"\nEnter array elements :: \n";

for(i=0; i<size; i++)


{
cout<<"\nEnter arr["<<i<<"] Element :: ";
cin>>a[i];
}

cout<<"\nStored Data in Array :: \n\n";

6
for(i=0;i<size;i++)
{
cout<<" "<<a[i]<<" ";
}
cout<<"\n\nEnter position to Delete number :: ";
cin>>pos;
if(pos>size)
{
cout<<"\nThis is out of range.\n";
}
else
{
--pos;
for(i=pos;i<=size-1;i++)
{
a[i]=a[i+1];
}
cout<<"\nNew Array is :: \n\n";
for(i=0;i<size-1;i++)
{
cout<<" "<<a[i]<<" ";
}
}
cout<<"\n";
return 0;

Output:

7
TASK-3
Write a program to find the location of a given element using Linear
Search.
#include<iostream>
using namespace std;
int main()
{
int arr[10], i, num, index;
cout<<"Enter 10 Numbers: ";
for(i=0; i<10; i++)
cin>>arr[i];
cout<<"\nEnter a Number to Search: ";
cin>>num;
for(i=0; i<10; i++)
{
if(arr[i]==num)
{

8
index = i;
break;
}
}
cout<<"\nFound at Index No."<<index;
cout<<endl;
return 0;
}

Output:

TASK-4
Write a program to find the location of a given element using Binary
Search.
#include<iostream>
using namespace std;
int main()
{
int i, arr[10], num, first, last, middle;
cout<<"Enter 10 Elements (in ascending order): ";

9
for(i=0; i<10; i++)
cin>>arr[i];
cout<<"\nEnter Element to be Search: ";
cin>>num;
first = 0;
last = 9;
middle = (first+last)/2;
while(first <= last)
{
if(arr[middle]<num)
first = middle+1;
else if(arr[middle]==num)
{
cout<<"\nThe number, "<<num<<" found at Position "<<middle+1;
break;
}
else
last = middle-1;
middle = (first+last)/2;
}
if(first>last)
cout<<"\nThe number, "<<num<<" is not found in given Array";
cout<<endl;
return 0;
}

Output:

10
TASK-5
Write a program to implement push and pop operations on a stack using
linear array.
#include <iostream>
using namespace std;
#define MAX_SIZE 1000
class Stack {
private:
int top;
int arr[MAX_SIZE];
public:
Stack() {
top = -1;
}

bool push(int x) {
if (top >= MAX_SIZE - 1) {
cout << "Stack is full" << endl;
return false;

11
}
arr[++top] = x;
return true;
}

int pop() {
if (top < 0) {
cout << "Stack underflow" << endl;
return 0;
}
return arr[top--];
}
int peek() {
if (top < 0) {
cout << "Stack is empty" << endl;
return 0;
}
return arr[top];
}
bool isEmpty() {
return (top < 0);
}
void display() {
if (top < 0) {
cout << "Stack is empty" << endl;
return;
}
cout << "\nStack elements: ";
for (int i = top; i >= 0; i--)

12
cout << arr[i] << " ";
cout << endl;
}
};
int main() {

cout << "Create a stack object:\n";


Stack s;
cout << "Check the stack is empty or not? ";
cout << s.isEmpty() << endl;
cout << "\nInsert some elements onto the stack:\n";
s.push(7);
s.push(6);
s.push(5);
s.push(4);
s.display();
cout << "\nRemove an element from the stack! ";
cout << s.pop();
s.display();
cout << "\nTop of the element of the stack:\n";
cout << s.peek();
cout << endl;
return 0;
}

Output:

13
TASK-6
Write a program to convert an infix expression to a postfix expression
using stacks.
#include <bits/stdc++.h>
using namespace std;
int prec(char c)
{
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
void infixToPostfix(string s)
{

stack<char> st;
string result;

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


char c = s[i];

14
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9'))
result += c;
else if (c == '(')
st.push('(');
else if (c == ')') {
while (st.top() != '(') {
result += st.top();
st.pop();
}
st.pop();
}
else {
while (!st.empty()
&& prec(s[i]) <= prec(st.top())) {
result += st.top();
st.pop();
}
st.push(c);
}
}
while (!st.empty()) {
result += st.top();
st.pop();
}
cout << result << endl;
}

int main()

15
{
string exp = "a+b*(c^d-e)^(f+g*h)-i";
infixToPostfix(exp);
return 0;
}

Output:

TASK-7
Write a program to evaluate a postfix expression using stacks.
#include<iostream>
#include<string.h>
#include<bits/stdc++.h>
using namespace std;
stack<int> s;

int main(){
string exp;
cout<<"Enter postfix expression: ";
cin>>exp;

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

if (isdigit(exp[i]))
s.push(exp[i] - '0');

16
int op2=s.top();
s.pop();
int op1=s.top();
s.pop();

if(exp[i]=='+')
s.push(op1+op2);
else if(exp[i]=='-')
s.push(op1-op2);
else if(exp[i]=='*')
s.push(op1*op2);
else if(exp[i]=='/')
s.push(op1/op2);
}
}
cout<<"After evalution we get: "<<s.top();
return 0;
}

Output:

TASK-8
Write a recursive function for Tower of Hanoi problem.
#include <iostream>
using namespace std;
void TOH(int n, char Sour, char Aux, char Des)

17
{
if (n == 1) {
cout << "Move Disk " << n << " from " << Sour << " to " << Des << endl;
return;
}

TOH(n - 1, Sour, Des, Aux);


cout << "Move Disk " << n << " from " << Sour << " to " << Des << endl;
TOH(n - 1, Aux, Sour, Des);
}

int main()
{
int n;

cout << "Enter no. of disks:";


cin >> n;
TOH(n, 'A', 'B', 'C');
return 0;
}

Output:

TASK-9

18
Write a program to implement insertion and deletion operations in a queue
using linear array.
#include <bits/stdc++.h>
using namespace std;
struct Queue {
int front, rear, size;
int* queue;
Queue(int c)
{
front = rear = 0;
size = c;
queue = new int;
}

~Queue() { delete[] queue; }


void enqueue(int element)
{
if (size == rear) {
cout<<"Queue is full"<<endl;
return;
}

else {
cout<<"Element inserted"<<endl;
queue[rear] = element;
rear++;
}
return;
}

19
void dequeue()
{

if (front == rear) {
cout<<"Queue is empty"<<endl;
return;
}
else {
for (int i = 0; i < rear - 1; i++) {
queue[i] = queue[i + 1];
}
cout<<"Element deleted"<<endl;

rear--;
}
return;
}
void printQueue()
{
if (front == rear) {
cout<<"Queue is Empty"<<endl;
return;
}

cout<<"The queue is: ";


for (int i = front; i < rear-1; i++) {
cout<<queue[i]<<" <-- ";
}
cout<<queue[rear-1]<<endl;

20
return;
}
void getFront()
{
if (front == rear) {
cout<<"The Queue is Empty"<<endl;
return;
}
cout<<"Front element is: "<< queue[front]<<endl;
return;
}
};
int main()
{
Queue queue(5);
queue.printQueue();
queue.enqueue(7);
queue.enqueue(4);
queue.enqueue(9);
queue.enqueue(6);
queue.printQueue();
queue.enqueue(1);

queue.printQueue();
queue.dequeue();
queue.printQueue();
queue.dequeue();
queue.printQueue();
queue.getFront();

21
return 0;
}

Output:

TASK-10
Write a menu driven program to perform following insertion operations in
a single linked list:
1 :Insertion at beginning:
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
void insertFront(Node** head, int data){

Node* new_node = new Node();


new_node->data = data;
new_node->next = *head;

*head = new_node;

22
cout << "Inserted Item: " << new_node->data << endl;
}
void printList(Node* node){

cout << "\nLinked List : " ;


while(node!=NULL){
cout << node->data << " "; node = node->next;
}
cout << endl;
}
int main(){
Node* head = NULL;
insertFront(&head,4);
insertFront(&head,5);
insertFront(&head,6);
insertFront(&head,7);
insertFront(&head,8);
insertFront(&head,9);
printList(head);
return 0;
}

Output:

23
2: Insertion at end:
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
};

void push(Node** head_ref, int new_data)


{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void append(Node** head_ref, int new_data)
{

Node* new_node = new Node();


new_node->data = new_data;

24
Node* last = *head_ref;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}

while (last->next != NULL) {


last = last->next;
}
last->next = new_node;
}
void printList(Node* node)
{
while (node != NULL) {
cout << " " << node->data;
node = node->next;
}
}

int main()
{
Node* head = NULL;
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
cout << "Created Linked list is: ";

25
printList(head);
append(&head, 1);
cout << "\nAfter inserting 1 at the end: ";
printList(head);

return 0;
}

Output:

3:Insertion after a given node:


#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
};
void insertAfter(Node* prev_node, int new_data)
{
if (prev_node == NULL) {
cout << "The given previous node cannot be NULL";
return;
}

26
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(Node* node)
{
while (node != NULL) {
cout << " " << node->data;
node = node->next;
}
cout << "\n";
}
int main()
{
Node* head = NULL;
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);

27
cout << "Created Linked list is: ";
printList(head);
insertAfter(head, 1);
cout << "After inserting 1 after 2: ";
printList(head);
return 0;
}

Output:

4: Traversing a linked list:


#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
LinkedList(){
head = NULL;
}
void push_back(int newElement) {
Node* newNode = new Node();

28
newNode->data = newElement;
newNode->next = NULL;
if(head == NULL) {
head = newNode;
} else {
Node* temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
}
void PrintList() {
Node* temp = head;
if(temp != NULL) {
cout<<"The list contains: ";
while(temp != NULL) {
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
} else {
cout<<"The list is empty.\n";
}
}
};
int main() {
LinkedList MyList;
MyList.push_back(10);
MyList.push_back(20);

29
MyList.push_back(30);
MyList.PrintList();
return 0;
}

Output:

TASK-11
Write a menu driven program to perform following deletion operations in
a single linked list:
1: Deletion at beginning:
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
void insertStart(Node** head, int data){
Node* new_node = new Node();
new_node->data = data;
new_node->next = *head;
*head = new_node;
}

30
void display(Node* node){
while(node!=NULL){
cout << node->data << " "; node = node->next;
}
cout << endl;
}
int main(){
Node* head = NULL;
insertStart(&head,10);
insertStart(&head,11);
insertStart(&head,12);
insertStart(&head,13);
insertStart(&head,14);
insertStart(&head,15);
insertStart(&head,16);
insertStart(&head,17);
insertStart(&head,18);
display(head);
return 0;
}

Output:

31
2: Deletion at end:
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
void deleteEnd (Node ** head)
{
Node *tempNode = *head;
Node *previous;
if (*head == NULL)
{
cout << ("\nEmpty List, can't delete");
return;
}
if (tempNode->next == NULL)
{
cout << "\nValue Deleted: " << (*head)->data;
*head = NULL;
return;
}
while (tempNode->next != NULL)
{
previous = tempNode;
tempNode = tempNode->next;
}

32
previous->next = NULL;
cout << "\nValue Deleted: " << tempNode->data;
free (tempNode);
}
void insert (Node ** head, int data)
{
Node *newNode = new Node ();
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
void display (Node * temp)
{
cout << "\nLinked List: ";
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
int main ()
{
Node *head = NULL;
insert (&head, 4);
insert (&head, 5);
insert (&head, 6);
insert (&head, 7);
insert (&head, 8);

33
insert (&head, 9);
insert (&head, 10);
display (head);
deleteEnd (&head);
deleteEnd (&head);
deleteEnd (&head);
display (head);
return 0;
}

Output:

3: Deletion after a given node:


#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();

34
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void deleteNode(Node **head_ref, int position)
{
if (*head_ref == NULL)
return;
Node* temp = *head_ref;
if (position == 0)
{
*head_ref = temp->next;
free(temp);
return;
}
for(int i = 0; temp != NULL && i < position - 1; i++)
temp = temp->next;
if (temp == NULL || temp->next == NULL)
return;
Node *next1 = temp->next->next;
free(temp->next);
temp->next = next1;
}
void printList( Node *node)
{
while (node != NULL)
{
cout << node->data << " ";
node = node->next;

35
}
}
int main()
{
Node* head = NULL;
push(&head, 7);
push(&head, 2);
push(&head, 5);
push(&head, 1);
cout << "Created Linked List: ";
printList(head);
deleteNode(&head, 2);
cout << "\nLinked List after Deletion at position 2: ";
printList(head);
return 0;
}

Output:

TASK-12
Write a program to implement push and pop operations on a stack using
linked list.
#include <iostream>
using namespace std;

36
class Node {
public:
int data;
Node* next;
};
class Stack {
private:
Node* top;
public:
Stack() {
top = NULL;
}
void push(int x) {
Node* newNode = new Node();
newNode->data = x;
newNode->next = top;
top = newNode;
}
void pop() {
if (top == NULL) {
cout << "Stack is empty!" << endl;
return;
}
Node* temp = top;
top = top->next;
delete temp;
}
void display() {
if (top == NULL) {

37
cout << "Stack is empty" << endl;
return;
}
Node* temp = top;
cout << "Stack elements are: ";
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
Stack stk;
cout << "Input some elements onto the stack (using linked list):\n";
stk.push(6);
stk.push(5);
stk.push(3);
stk.push(1);
stk.display();
cout << "\nRemove 2 elements from the stack:\n";
stk.pop();
stk.pop();
stk.display();
cout << "\nInput 2 more elements:\n";
stk.push(8);
stk.push(9);
stk.display();
return 0; }

38
Output:

TASK-13
Write a program to implement push and pop operations on a queue using
linked list.
#include <iostream>
using namespace std;
struct node {
int data;
struct node *next;
};
struct node* front = NULL;
struct node* rear = NULL;
struct node* temp;
void Insert() {
int val;
cout<<"Insert the element in queue : "<<endl;
cin>>val;
if (rear == NULL) {
rear = (struct node *)malloc(sizeof(struct node));
rear->next = NULL;
rear->data = val;
front = rear;
} else {
temp=(struct node *)malloc(sizeof(struct node));
39
rear->next = temp;
temp->data = val;
temp->next = NULL;
rear = temp;
}
}
void Delete() {
temp = front;
if (front == NULL) {
cout<<"Underflow"<<endl;
return;
}
else
if (temp->next != NULL) {
temp = temp->next;
cout<<"Element deleted from queue is : "<<front->data<<endl;
free(front);
front = temp;
} else {
cout<<"Element deleted from queue is : "<<front->data<<endl;
free(front);
front = NULL;
rear = NULL;
}
}
void Display() {
temp = front;
if ((front == NULL) && (rear == NULL)) {
cout<<"Queue is empty"<<endl;

40
return;
}
cout<<"Queue elements are: ";
while (temp != NULL) {
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
int main() {
int ch;
cout<<"1) Insert element to queue"<<endl;
cout<<"2) Delete element from queue"<<endl;
cout<<"3) Display all the elements of queue"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter your choice : "<<endl;
cin>>ch;
switch (ch) {
case 1: Insert();
break;
case 2: Delete();
break;
case 3: Display();
break;
case 4: cout<<"Exit"<<endl;
break;
default: cout<<"Invalid choice"<<endl;
}

41
} while(ch!=4);
return 0;
}

Output:

TASK-14
Program to sort an array of integers in ascending order using bubble sort.
#include<iostream>
using namespace std;
int main()
{
int num, i, arr[50], j, temp;
cout<<"\n Enter Total Number of Elements : ";
cin>>num;
cout<<"\n Enter "<<num<<" Elements : \n\n";
for(i=0; i<num; i++)
{
cout<<" ";
cin>>arr[i];
}
cout<<"\n\n Sorting Array using Bubble Sort... \n";

42
for(i=0; i<(num-1); i++)
{
for(j=0; j<(num-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}}}
cout<<"\n Sorted Element in Ascending Order : \n";

for(i=0; i<num; i++)


{
cout<<" ";
cout<<ar0r[i]<<" ";
}
return 0;
}

Output:

TASK-15

43
Program to sort an array of integers in ascending order using selection sort.
#include<bits/stdc++.h>
using namespace std;
void print(int arr[], int n)
{
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
void selectionSort(int arr[], int n)
{
int i,j,min_in;
for(i=0;i<n;i++)
{
min_in = i;
for(j=i+1;j<n;j++)
if (arr[j] < arr[min_in])
min_in = j;
swap(arr[i],arr[min_in]);
}
}
int main(int argv, char* argc[])
{
int arr[] = {5,4,10,1,6,2};
int i,j,n,temp;
n = sizeof(arr)/sizeof(int);
cout<<"Unsorted Array :";
print(arr,n);
selectionSort(arr,n);

44
cout<<"Sorted Array :";
print(arr,n);
return(0);
}

Output:

TASK-16
Program to sort an array of integers in ascending order using insertion sort.
#include<iostream>
using namespace std;
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void insertionSort(int *array, int size) {
int key, j;
for(int i = 1; i<size; i++) {
key = array[i];
j = i;
while(j > 0 && array[j-1]>key) {
array[j] = array[j-1];
j--;
}
array[j] = key;

45
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
insertionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}

Output:

TASK-17

46
Program to sort an array of integers in ascending order using quick sort.
#include<iostream>
using namespace std;
void swap(int arr[] , int pos1, int pos2){
int temp;
temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
int partition(int arr[], int low, int high, int pivot){
int i = low;
int j = low;
while( i <= high){
if(arr[i] > pivot){
i++;
}
else{
swap(arr,i,j);
i++;
j++;
}
}
return j-1;
}
void quickSort(int arr[], int low, int high){
if(low < high){
int pivot = arr[high];
int pos = partition(arr, low, high, pivot);

quickSort(arr, low, pos-1);

47
quickSort(arr, pos+1, high);
}
}
int main()
{
int n ;
cout << " enter the size of array";
cin>>n;
int arr[n];
for( int i = 0 ; i < n; i++){
cin>> arr[i];
}
quickSort(arr, 0 , n-1);
cout<<"The sorted array is: ";
for( int i = 0 ; i < n; i++){
cout<< arr[i]<<"\t";
}
}

Output:

48
TASK-18
Program to traverse a Binary search tree in In-order, Pre-order and Post-
order:
In-order:
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int v)
{
this->data = v;
this->left = this->right = NULL;
}
};
void printInorder(Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
cout << node->data << " ";
printInorder(node->right);
}
int main()
{
Node* root = new Node(100);
root->left = new Node(20);
root->right = new Node(200);

49
root->left->left = new Node(10);
root->left->right = new Node(30);
root->right->left = new Node(150);
root->right->right = new Node(300);
cout << "Inorder Traversal: ";
printInorder(root);
return 0;
}

Output:

Pre-order:
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int v)
{
this->data = v;
this->left = this->right = NULL;
}
};
void printPreOrder(Node* node)
{
if (node == NULL)

50
return;
cout << node->data << " ";
printPreOrder(node->left);
printPreOrder(node->right);
}
int main()
{
Node* root = new Node(100);
root->left = new Node(20);
root->right = new Node(200);
root->left->left = new Node(10);
root->left->right = new Node(30);
root->right->left = new Node(150);
root->right->right = new Node(300);
cout << "Preorder Traversal: ";
printPreOrder(root);
return 0;
}

Output:

Post-order:
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;

51
Node* right;
Node(int v)
{
this->data = v;
this->left = this->right = NULL;
}
};
void printPostOrder(Node* node)
{
if (node == NULL)
return;
printPostOrder(node->left);
printPostOrder(node->right);
cout << node->data << " ";
}
int main()
{
Node* root = new Node(100);
root->left = new Node(20);
root->right = new Node(200);
root->left->left = new Node(10);
root->left->right = new Node(30);
root->right->left = new Node(150);
root->right->right = new Node(300);
cout << "PostOrder Traversal: ";
printPostOrder(root);
cout << "\n";

return 0;
}

52
Output:

TASK-19
Program to traverse graphs using BFS.
#include <bits/stdc++.h>
using namespace std;
class Graph {
int V;
vector<list<int> > adj;
public:
Graph(int V);
void addEdge(int v, int w);
void BFS(int s);
};

Graph::Graph(int V)
{
this->V = V;
adj.resize(V);
}

void Graph::addEdge(int v, int w)


{

53
adj[v].push_back(w);
}

void Graph::BFS(int s)
{
vector<bool> visited;
visited.resize(V, false);
list<int> queue;
visited[s] = true;
queue.push_back(s);

while (!queue.empty()) {
s = queue.front();
cout << s << " ";
queue.pop_front();
for (auto adjacent : adj[s]) {
if (!visited[adjacent]) {
visited[adjacent] = true;
queue.push_back(adjacent);
}
}
}
}

int main()
{

Graph g(4);
g.addEdge(0, 1);

54
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

cout << "Following is Breadth First Traversal "


<< "(starting from vertex 2) \n";
g.BFS(2);

return 0;
}

Output:

TASK-20
Program to traverse graphs using DFS.
#include <bits/stdc++.h>
using namespace std;
class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;
void addEdge(int v, int w);
void DFS(int v);
};

55
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
}

void Graph::DFS(int v)
{
visited[v] = true;
cout << v << " ";
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFS(*i);
}
int main()
{
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

cout << "Following is Depth First Traversal"


" (starting from vertex 2) \n";
g.DFS(2);

return 0;

56
}

Output:

57

You might also like