0% found this document useful (0 votes)
25 views

Data Structure Practical

Uploaded by

Pankaj Desai
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Data Structure Practical

Uploaded by

Pankaj Desai
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )

1). Write a program to accept the elements in 2D array and perform all the matrix operations i.e.
addition, multiplication, transpose etc.

A] #include<iostream>
using namespace std;

#define s 20
class matrix
{
int a[s][s],x,y,i,j;
//static int n;
public:
void get();
void put();
matrix operator+(matrix);
matrix operator-(matrix);
matrix operator*(matrix);
matrix transpose();
};
void matrix::get()
{
cout<<"Enter the order of Matrix "<<" :\n";
cin>>x>>y;
cout<<"Enter the Matrix "<<" :\n";
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
cin>>a[i][j];

}
void matrix::put()
{
cout<<"The Ans is:\n";
for(int i=0;i<x;i++)
{
cout<<"\n\t";
for(int j=0;j<y;j++)
cout<<a[i][j]<<" ";
}
}
matrix matrix::operator+(matrix b)
{
matrix r;
if((x!=b.x)||(y!=b.y))
{
cout<<"\n\tMatrix Addition is not possible the result is incorrect\n\n";
r.x=0;
r.y=0;
}
else
{
r.x=x;
r.y=y;
}
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
r.a[i][j]=a[i][j]+b.a[i][j];
return r;
}
matrix matrix::operator-(matrix b)
{
matrix r;
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
if((x!=b.x)||(y!=b.y))
{
cout<<"\n\tMatrix subtraction is not possible the result is incorrect\n\n";
r.x=0;
r.y=0;
}
else
{
r.x=x;
r.y=y;
}
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
r.a[i][j]=a[i][j]-b.a[i][j];

return r;
}
matrix matrix::operator*(matrix b)
{
matrix r;
if((x!=b.y)||(y!=b.x))
{
cout<<"\n\tMatrix Multiplication is not possible the result is incorrect\n\n";
r.x=0;
r.y=0;
}
else
{
r.x=x;
r.y=b.y;
}
for(int i=0;i<s;i++)
for(int j=0;j<s;j++)
r.a[i][j]=0;
for(i=0;i<x;i++)
for(j=0;j<b.y;j++)
for(int k=0;(k<y)||(k<b.x);k++)
r.a[i][j]+=a[i][k]*b.a[k][j];

return r;
}
matrix matrix::transpose()
{
matrix r;
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
r.a[i][j]=a[j][i];
r.x=x;
r.y=y;
return r;
}

//..........................Main function..................................

int main()
{
matrix a,b,c;
int t=1,

while(t)
{
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
cout<<"\tSelect Option\n\n1.Matrix Addition\n2.Matrix Subtration\n3.Matrix Multiplication\n4.Matrix
Transponse\n5.Exit\n";

switch()
{
case'1':
cout<<"\n\tMatrix Addiation\n";
a.get();
b.get();
c=a+b;
c.put();
break;
case'2':
cout<<"\n\tMatrix Subtration\n";
a.get();
b.get();
c=a-b;
c.put();
break;
case'3':
cout<<"\n\tMatrix Multpication\n";
a.get();
b.get();
c=a*b;
c.put();
break;
case'4':
cout<<"\n\tMatrix Transpose\n";
a.get();
c=a.transpose();
c.put();
break;
case'5':
cout<<"\n\tPress any key to exit\n";
t=0;
break;
default:
cout<<"\n\tEnter a valid option\n";

}
return 0;
}

return 0;
}
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
2). Explain following techniques  Bubble sort  Insertion sort  Radix sort

A]
1). Bubble sort,
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps
through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass
through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named
for the way smaller or larger elements "bubble" to the top of the list.
Step-by-step example
Take an array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using
bubble sort. In each step, elements written in bold are being compared. Three passes will be required;
First Pass
( 5 1 4 2 8 ) → ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) → ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) → ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) → ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not
swap them.
Second Pass
(14258)→(14258)
( 1 4 2 5 8 ) → ( 1 2 4 5 8 ), Swap since 4 > 2
(12458)→(12458)
(12458)→(12458)
Now, the array is already sorted, but the algorithm does not know if it is completed. The algorithm
needs one additional whole pass without any swap to know it is sorted.
Third Pass
(12458)→(12458)
(12458)→(12458)
(12458)→(12458)
(12458)→(12458)

2). Insertion sort


Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a
time. It is much less efficient on large lists than more advanced algorithms such
as quicksort, heapsort, or merge sort.
Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the elements before. Move the
greater elements one position up to make space for the swapped element.
Example:
12, 11, 13, 5, 6
Let us loop for i = 1 (second element of the array) to 4 (last element of the array)
i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12
11, 12, 13, 5, 6
i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13
11, 12, 13, 5, 6
i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one position
ahead of their current position.
5, 11, 12, 13, 6
i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position ahead of
their current position.
5, 6, 11, 12, 13
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )

3). Radix sort


In computer science, radix sort is a non-comparative sorting algorithm. It avoids comparison by
creating and distributing elements into buckets according to their radix. For elements with more
than one significant digit, this bucketing process is repeated for each digit, while preserving the
ordering of the prior step, until all digits have been considered.
Example:
riginal, unsorted list:
170, 45, 75, 90, 802, 24, 2, 66

Sorting by least significant digit (1s place) gives:


[*Notice that we keep 802 before 2, because 802 occurred
before 2 in the original list, and similarly for pairs
170 & 90 and 45 & 75.]

170, 90, 802, 2, 24, 45, 75, 66

Sorting by next digit (10s place) gives:


[*Notice that 802 again comes before 2 as 802 comes before
2 in the previous list.]

802, 2, 24, 45, 66, 170, 75, 90

Sorting by the most significant digit (100s place) gives:


2, 24, 45, 66, 75, 90, 170, 802
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
3). Suppose an array contains n elements. Given a number x that may occur several times in the
array. Write a program to find.
i. The number of occurrences of x in the array.
A] We first find an occurrence using binary search. Then we match toward left and right sides of
the matched the found index.

#include<bits/stdc++.h>
using namespace std;
// Returns number of times x occurs in arr[0..n-1]
int countOccurrences(int arr[], int n, int x)
{ int res = 0;
for (int i=0; i<n; i++)
if (x == arr[i])
res++;
return res;
}
// Driver code
int main()
{ int arr[] = {1, 2, 2, 2, 2, 3, 4, 7 ,8 ,8 };
int n = sizeof(arr)/sizeof(arr[0]);
int x = 2;
cout << countOccurrences(arr, n, x);
return 0;
}
Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 2
Output: 4 // x (or 2) occurs 4 times in arr[]
ii. The position of first occurrence of x in the array.
#include <bits/stdc++.h>
using namespace std;
// Function for finding first occurrence
// of an elements
void findFirst(int arr[], int n, int x)
{ int first = -1;
for (int i = 0; i < n; i++) {
if (x != arr[i])
continue;
if (first == -1)
first = i; }
if (first != -1)
cout << "First Occurrence = " << first;
else
cout << "Not Found";
}
// Driver code
int main()
{ int arr[] = { 1, 2, 2, 2, 2, 3, 4, 7, 8, 8 };
int n = sizeof(arr) / sizeof(int);
int x = 8;
findFirst(arr, n, x);
return 0; }
Input : arr[] = {1, 3, 5, 5, 5, 5, 67, 123, 125}
x=5
Output : First Occurrence = 2
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
4). Write a program in C++ to delete particular element from an array of 10 integers.

A] #include<iostream>
using namespace std;
int main()
{
int arr[10], tot=10, i, elem, j, found=0;
cout<<"Enter 10 Array Elements: ";
for(i=0; i<tot; i++)
cin>>arr[i];
cout<<"\nEnter Element to Delete: ";
cin>>elem;
for(i=0; i<tot; i++)
{
if(arr[i]==elem)
{
for(j=i; j<(tot-1); j++)
arr[j] = arr[j+1];
found++;
i--;
tot--;
}
}
if(found==0)
cout<<"\nElement doesn't found in the Array!";
else
cout<<"\nElement Deleted Successfully!";
cout<<endl;
return 0;
}

Output:
Enter Element to Delete: 1,2,3,4,5,6,7,8,9,10
Enter Element to Delete:8
Element Deleted Successfully!"
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
5). Consider two single dimensional array of size 20 and 3 respectively. Write a program in C++ to
display all the elements which are common in both arrays.

A] #include <bits/stdc++.h>
using namespace std;

// This function prints common elements in ar1


void findCommon(int ar1[], int ar2[], int n1,int n2);
{
// Initialize starting indexes for ar1[], ar2[]
int i = 0, j = 0;

// Iterate through two arrays while all arrays have


// elements
while (i < n1 && j < n2)
// If x = y and y = x, print any of them and move
// ahead in all arrays
if (ar1[i] == ar2[j] && ar2[j])
{
cout << ar1[i] << " ";
i++;
j++;
}

// x < y
else if {
(ar1[i] < ar2[j])
i++;
}
}

// Driver code
int main()
{
int ar1[] = { 1, 5, 10, 20, 40, 80,50,88,87,55 };
int ar2[] = { 6, 7, 55 };
int n1 = sizeof(ar1) / sizeof(ar1[0]);
int n2 = sizeof(ar2) / sizeof(ar2[0]);

cout << "Common Elements are ";


findCommon(ar1, ar2, n1, n2);
return 0;
}

Input:
ar1[] = { 1, 5, 10, 20, 40, 80,50,88,87,55 }
ar2[] = { 6, 5, 55 }
Output: 5, 55
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
6). Write a program to build a sparse matrix as an array. Write functions to check if the sparse
matrix is a square, diagonal, lower triangular, upper triangular or tridiagonal matrix.

A]
// C++ program to print Lower
// triangular and Upper triangular
// matrix of an array
#include<iostream>

using namespace std;

// Function to form
// lower triangular matrix
void lower(int matrix[3][3], int row, int col)
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (i < j)
{
cout << "0" << " ";
}
else
cout << matrix[i][j] << " ";
}
cout << endl;
}
}

// Function to form upper triangular matrix


void upper(int matrix[3][3], int row, int col)
{
int i, j;

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


{
for (j = 0; j < col; j++)
{
if (i > j)
{
cout << "0" << " ";
}
else
cout << matrix[i][j] << " ";
}
cout << endl;
}
}

// Driver Code
int main()
{
int matrix[3][3] = {{1, 2, 3},
{4, 5, 6},
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
{7, 8, 9}};
int row = 3, col = 3;

cout << "Lower triangular matrix: \n";


lower(matrix, row, col);

cout << "Upper triangular matrix: \n";


upper(matrix, row, col);

return 0;
}

Input : matrix[3][3] = {1 2 3
456
7 8 9}
Output :
Lower : 1 0 0 Upper : 1 2 3
450 056
789 009
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
7). Write a menu driven program for stack contain following function  PUSH  POP  DISPLAY 
PEE

A]
/* C++ program to implement basic stack operations */

#include <bits/stdc++.h>
using namespace std;
#define MAX 1000

class Stack {
int top;

public:
int a[MAX]; // Maximum size of Stack

Stack() { top = -1; }


bool push(int x);
int pop();
int peek();
bool isEmpty();
};

bool Stack::push(int x)
{
if (top >= (MAX - 1)) {
cout << "Stack Overflow";
return false;
}
else {
a[++top] = x;
cout << x << " pushed into stack\n";
return true;
}
}

int Stack::pop()
{
if (top < 0) {
cout << "Stack Underflow";
return 0;
}
else {
int x = a[top--];
return x;
}
}
int Stack::peek()
{
if (top < 0) {
cout << "Stack is Empty";
return 0;
}
else {
int x = a[top];
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
return x;
}
}

bool Stack::isEmpty()
{
return (top < 0);
}

// Driver program to test above functions


int main()
{
class Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " Popped from stack\n";
//print all elements in stack :
cout<<"Elements present in stack : ";
while(!s.isEmpty())
{
// print top element in stack
cout<<s.peek()<<" ";
// remove top element in stack
s.pop();
}

return 0;
}

Output:
10 pushed into stack
20 pushed into stack
30 pushed into stack
30 Popped from stack
Elements preset in stack : 20 10
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
8). Transform the following infix expressions into their equivalent prefix expressions:
(A-B) *(D/ E)
(A+B^D) / (E-F) + G
A* (B+D) / E -F* (G + H/ K

A]
Output for "(A-B) *(D/ E)" expression
Step 1. Reversed string: (E /D)* (B-A)
Step 2. Postfix of (E /D)* (B-A): E D/ BA-*
Step 3. Reversed string of E D/ BA-* is *-AB /D E

Input String Output Stack Operator Stack


(E /D)* (B-A) (
(E /D)* (B-A) E (
(E /D)* (B-A) E (
(E /D)* (B-A) E (/
(E /D)* (B-A) E D (/
(E /D)* (B-A) E D/
(E /D)* (B-A) E D/ *
(E /D)* (B-A) E D/ *
(E /D)* (B-A) E D/ *(
(E /D)* (B-A) E D/ B *(
(E /D)* (B-A) E D/ B *(-
(E /D)* (B-A) E D/ BA *(-
(E /D)* (B-A) E D/ BA- *
(E /D)* (B-A) E D/ BA-*
So final (A-B) *(D/ E) is an Infix equation converted to Prefix as *-AB /D E
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
Step by step output for "(A+B^D) / (E-F) + G" expression
Reversed string: G + (F-E) / (D^B+A)
Postfix of G + (F-E) / (D^B+A): G FE- DB^A+/+

Input String Output Stack Operator Stack


G + (F-E) / (D^B+A) G
G + (F-E) / (D^B+A) G
G + (F-E) / (D^B+A) G +
G + (F-E) / (D^B+A) G +
G + (F-E) / (D^B+A) G +(
G + (F-E) / (D^B+A) GF +(
G + (F-E) / (D^B+A) GF +(-
G + (F-E) / (D^B+A) G FE +(-
G + (F-E) / (D^B+A) G FE- +
G + (F-E) / (D^B+A) G FE- +
G + (F-E) / (D^B+A) G FE- +/
G + (F-E) / (D^B+A) G FE- +/
G + (F-E) / (D^B+A) G FE- +/(
G + (F-E) / (D^B+A) G FE- D +/(
G + (F-E) / (D^B+A) G FE- D +/(^
G + (F-E) / (D^B+A) G FE- DB +/(^
G + (F-E) / (D^B+A) G FE- DB^ +/(+
G + (F-E) / (D^B+A) G FE- DB^A +/(+
G + (F-E) / (D^B+A) G FE- DB^A+ +/
G + (F-E) / (D^B+A) G FE- DB^A+/+

Reversed string of G FE- DB^A+/+ is +/+A^BD -EF G


So final (A+B^D) / (E-F) + G is an Infix equation converted to Prefix as +/+A^BD -EF
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
Step by step output for "A* (B+D) / E -F* (G + H/ K)" expression
Reversed string: (K /H + G) *F- E / (D+B) *A

Postfix of (K /H + G) *F- E / (D+B) *A is K H / G+ F* E DB+ /A*-

Input String Output Stack Operator Stack


(K /H + G) *F- E / (D+B) *A (
(K /H + G) *F- E / (D+B) *A K (
(K /H + G) *F- E / (D+B) *A K (
(K /H + G) *F- E / (D+B) *A K (/
(K /H + G) *F- E / (D+B) *A KH (/
(K /H + G) *F- E / (D+B) *A KH (/
(K /H + G) *F- E / (D+B) *A KH/ (+
(K /H + G) *F- E / (D+B) *A KH/ (+
(K /H + G) *F- E / (D+B) *A KH/G (+
(K /H + G) *F- E / (D+B) *A K H / G+
(K /H + G) *F- E / (D+B) *A K H / G+
(K /H + G) *F- E / (D+B) *A K H / G+ *
(K /H + G) *F- E / (D+B) *A K H / G+ F *
(K /H + G) *F- E / (D+B) *A K H / G+ F* -
(K /H + G) *F- E / (D+B) *A K H / G+ F* -
(K /H + G) *F- E / (D+B) *A K H / G+ F* E -
(K /H + G) *F- E / (D+B) *A K H / G+ F* E -
(K /H + G) *F- E / (D+B) *A K H / G+ F* E -/
(K /H + G) *F- E / (D+B) *A K H / G+ F* E -/
(K /H + G) *F- E / (D+B) *A K H / G+ F* E -/(
(K /H + G) *F- E / (D+B) *A K H / G+ F* E D -/(
(K /H + G) *F- E / (D+B) *A K H / G+ F* E D -/(+
(K /H + G) *F- E / (D+B) *A K H / G+ F* E DB -/(+
(K /H + G) *F- E / (D+B) *A K H / G+ F* E DB+ -/
(K /H + G) *F- E / (D+B) *A K H / G+ F* E DB+ -/
(K /H + G) *F- E / (D+B) *A K H / G+ F* E DB+ / -*
(K /H + G) *F- E / (D+B) *A K H / G+ F* E DB+ /A -*
(K /H + G) *F- E / (D+B) *A K H / G+ F* E DB+ /A*-
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
9). Write a program in C++ to implement queue using Array.

A] A program that implements the queue using an array is given as follows:


#include <iostream>
using namespace std;
int queue[100], n = 100, front = - 1, rear = - 1;
void Insert() {
int val;
if (rear == n - 1)
cout<<"Queue Overflow"<<endl;
else {
if (front == - 1)
front = 0;
cout<<"Insert the element in queue : "<<endl;
cin>>val;
rear++;
queue[rear] = val;
}
}
void Delete() {
if (front == - 1 || front > rear) {
cout<<"Queue Underflow ";
return ;
} else {
cout<<"Element deleted from queue is : "<< queue[front] <<endl;
front++;;
}
}
void Display() {
if (front == - 1)
cout<<"Queue is empty"<<endl;
else {
cout<<"Queue elements are : ";
for (int i = front; i <= rear; i++)
cout<<queue[i]<<" ";
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;
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
default: cout<<"Invalid choice"<<endl;
}
} while(ch!=4);
return 0;
}

Output:
1) Insert element to queue
2) Delete element from queue
3) Display all the elements of queue
4) Exit
Enter your choice : 1
Insert the element in queue : 4
Enter your choice : 1
Insert the element in queue : 3
Enter your choice : 1
Insert the element in queue : 5
Enter your choice : 2
Element deleted from queue is : 4
Enter your choice : 3
Queue elements are : 3 5
Enter your choice : 7
Invalid choice
Enter your choice : 4
Exit
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
10). Write menu driven program which create and display the circular linked list.

A]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//Represents the node of list.
struct node{
int data;
struct node *next;
};

//Declaring head and tail pointer as null.


struct node *head = NULL;
struct node *tail = NULL;

//This function will add the new node at the end of the list.
void add(int data){
//Create new node
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
//Checks if the list is empty.
if(head == NULL){
//If list is empty, both head and tail would point to new node.
head = newNode;
tail = newNode;
newNode->next = head;
}else {
//tail will point to new node.
tail->next = newNode;
//New node will become new tail.
tail = newNode;
//Since, it is circular linked list tail will point to head.
tail->next = head;
}
}

//This function will display the nodes of circular linked list


void display(){
struct node *current = head;
if(head == NULL){
printf("List is empty");
}
else{
printf("Nodes of the circular linked list: \n");
do{
//Prints each node by incrementing pointer.
printf("%d ", current->data);
current = current->next;
}while(current != head);
printf("\n");
}
}

int main()
{
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
//Adds data to the list
add(1);
add(2);
add(3);
add(4);
//Displays all the nodes present in the list
display();

return 0;
}

Output:
Nodes of the circular linked list:
1234
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
11). Create binary search tree 15, 2, 25, 45, 35, 23, 100, 5

A] The process of creating the BST is shown below –


ROOT

15

2 25

5 35 45

23 100
35

Step 1 - Insert 15.


As root
Step 2 - Insert 2.
As 2 is smaller than 15, so insert it as the root node of the left subtree.
Step 3 - Insert 25.
As 25 is greater than 15, so insert it as the root node of the right subtree.
Step 4 - Insert 45.
45 is greater than 15 and 25, so it will be inserted as the right subtree of 25.
Step 5 - Insert 35.
35 is greater than 15 and smaller than 45, so it will be inserted as the left subtree of 25.
Step 6 - Insert 23.
23 is greater than 15 but smaller than 25 and 35. So, it will be inserted as a left subtree of 35
Step 7 - Insert 100.
100 is greater than 15 and 45 , so it will be inserted as the right subtree of 45.
Step 7 - Insert 5.
5 is smaller than 15 but greater than 2, so it will be inserted as the right subtree of 2.

the creation of binary search tree is completed


PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )

12). Given two binary trees, write a program that finds whether –
The two binary trees are similar. –
the two binary trees are mirror images of each other
// C++ program to check if two trees are mirror
// of each other
#include<bits/stdc++.h>
using namespace std;

/* A binary tree node has data, pointer to


left child and a pointer to right child */
struct Node
{
int data;
Node* left, *right;
};

/* Given two trees, return true if they are


mirror of each other */
/*As function has to return bool value instead integer value*/
bool areMirror(Node* a, Node* b)
{
/* Base case : Both empty */
if (a==NULL && b==NULL)
return true;

// If only one is empty


if (a==NULL || b == NULL)
return false;
/* Both non-empty, compare them recursively
Note that in recursive calls, we pass left
of one tree and right of other tree */
return a->data == b->data &&
areMirror(a->left, b->right) &&
areMirror(a->right, b->left);
}
/* Helper function that allocates a new node */
Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return(node);
}

/* Driver program to test areMirror() */


int main()
{
Node *a = newNode(1);
Node *b = newNode(1);
a->left = newNode(2);
a->right = newNode(3);
a->left->left = newNode(4);
a->left->right = newNode(5);
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
b->left = newNode(3);
b->right = newNode(2);
b->right->left = newNode(5);
b->right->right = newNode(4);

areMirror(a, b)? cout << "Yes" : cout << "No";

return 0;
}

Output :
Yes

ii. the two binary trees are mirror images of each other
#include <iostream>
// Define node structure
struct node{
int data;
struct node* left,*right;
// Constructor
node(int x){
data = x;
left = right = NULL; }
};
bool mirror_image_check(struct node* root1,struct node* root2){
if((root1==NULL) and (root2==NULL))return true; // If both trees are empty, then they are mirror image
if((!root1 and root2) or (root1 and !root2))return false; // If either of the tree is empty, when other is not, they
cannot be mirror to each other
bool left_check = mirror_image_check(root1->left,root2->right); // Check if left subtree in tree 1 is mirror to right
subtree in tree 2
bool right_check = mirror_image_check(root1->right,root2->left);// Check if right subtree in tree 1 is mirror to left
subtree in tree 2.
return (root1->data == root2->data) and left_check and right_check ; // Check if root nodes are same, and also the
subtrees condition for mirror. }
int main() {
// Construct tree 1
struct node* root1 = new node(1);
root1->left = new node(2);
root1->right = new node(3);
root1->left->left = new node(4);
root1->left->right = new node(5);
// Construct tree 2
struct node* root2 = new node(1);
root2->left = new node(3);
root2->right = new node(2);
root2->right->left = new node(5);
root2->right->right = new node(4);
if(mirror_image_check(root1,root2)){ // Function to check if two trees are mirror image to each other
std::cout<<"Yes,the trees are mirror image of each other\n";
}else{
std::cout<<"No, the trees are not mirror image of each other\n";
}
return 0; }
Output :
Yes,the trees are mirror image of each other
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )

13). Write a program to traverse the graph using BFS method.

A]

// Program to print BFS traversal from a given


// source vertex. BFS(int s) traverses vertices
// reachable from s.
#include<bits/stdc++.h>
using namespace std;

// This class represents a directed graph using


// adjacency list representation
class Graph
{
int V; // No. of vertices

// Pointer to an array containing adjacency


// lists
vector<list<int>> adj;
public:
Graph(int V); // Constructor

// function to add an edge to graph


void addEdge(int v, int w);

// prints BFS traversal from a given source s


void BFS(int s);
};

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

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


{
adj[v].push_back(w); // Add w to v’s list.
}

void Graph::BFS(int s)
{
// Mark all the vertices as not visited
vector<bool> visited;
visited.resize(V,false);

// Create a queue for BFS


list<int> queue;
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )

// Mark the current node as visited and enqueue it


visited[s] = true;
queue.push_back(s);

while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();

// Get all adjacent vertices of the dequeued


// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (auto adjecent: adj[s])
{
if (!visited[adjecent])
{
visited[adjecent] = true;
queue.push_back(adjecent);
}
}
}
}

// Driver program to test methods of graph class


int main()
{
// Create a graph given in the above diagram
Graph g(4);
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 Breadth First Traversal "


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

return 0;
}

Output:
Following is Breadth First Traversal (starting from vertex 2)
2031
PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
14). Write a program to traverse the graph using DFS method.

A]
// C++ program to print DFS traversal from
// a given vertex in a given graph
#include <bits/stdc++.h>
using namespace std;

// Graph class represents a directed graph


// using adjacency list representation
class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;

// function to add an edge to graph


void addEdge(int v, int w);

// DFS traversal of the vertices


// reachable from v
void DFS(int v);
};

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


{
adj[v].push_back(w); // Add w to v’s list.
}

void Graph::DFS(int v)
{
// Mark the current node as visited and
// print it
visited[v] = true;
cout << v << " ";

// Recur for all the vertices adjacent


// to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFS(*i);
}

// Driver code
int main()
{
// Create a graph given in the above diagram
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"


PRN: 2021017001608861 Yash Parmar FYBCA – SEM-II (Data Srtucture Using C++ )
" (starting from vertex 2) \n";
g.DFS(2);

return 0;
}

Output:
Following is Depth First Traversal
01239

You might also like