You are on page 1of 76

Data Structures(DS)

SUBJECT CODE:
CO252-LAB FILE
Submitted by –
KANISHKA SAPRA (2K21/BT/14)
Submitted to –
Prof. POONAM

DEPARTMENT OF BIOTECHNOLOGY

DELHI TECHNOLOGICAL UNIVERSITY,


SHAHBADDAULATPUR
(FORMERLY DELHI COLLEGE OF ENGINEERING)

1
CERTIFICATE

This is to certify that KANISHKA SAPRA, roll no. 2K21/BT/14, a student of B.Tech Biotechnology, has
successfully completed the laboratory work for the subject Data Structure and Algorithms (subject code CO252)
during the academic year 2022-2023 in the second year of the Bachelor of Technology program at Delhi
Technological University.

Signature of the Teacher: ____________


Date: ____________

2
DATA STRUCTURES AND ALGORITHM PRACTICALS

Program Experiments Page no


no.
1. Write a program to Implement Linear Search in C programming language 3-5

2 Write a program to Implement Binary Search in C programming language. 6-8


Assume the list is already sorted
3 Write a program to implement the bubble sort and also write its applications 9 - 11
4 Write a program to implement the Merge Sort and also write its applications. 12 -15
5 Write a program to insert an element at the mid position in the One-dimensional 16 - 17
array
6 Write a program Implement a stack data structure and perform its operations.
18- 22
7 Write a program to implement two stack using single array 23 - 28

8 Write a program to find minimum element of stack in constant time 29 - 31

9 Write a program to implement Queue Data structure. 32 - 35

10 Write a program to reverse first k elements of a given Queue 36 - 40

11 Write a program to check weather given string is Palindrome or not using 41 - 45


DEQUEUE
12 Write a program to implement Tower of Hanoi using stack data structure
46 - 50
13 Write a Program to find nearest smallest element on the left side of the element 51 - 53
in the array
14 Given a Sorted doubly linked list of positive integers and an integer, then finds 54 - 56
all the pairs (sum of two nodes data part) that are equal to the given integer
value.
15 Write a program to find the middle element of the given linked list in a single pass. 57 - 59

16 Write a program to check whether given tree is binary search tree or not. 60 – 62
17 Write a program to implement insertion in AVL tree 63 - 66
18 Write a program to print spiral order of a Binary Tree. 67 - 70
19 Write a program to print the left view of the Binary Tree 71 - 74

3
Experiment-1

Write a program to Implement Linear Search in C programming language.

Objective: To find the desired element in an array or report it’s absence by using Linear Search

Theory: Linear Search is the simplest searching algorithm. It traverses the array sequentially to
locate the required element. It searches for an element by comparing it with each element of the
array one by one. So, it is also called as Sequential Search. It’s Time complexity is O(N), where
N is the size of the array.

Algorithm: Consider-
• There is a linear array ‘a’ of size 10.
• Linear search algorithm is being used to search an element ‘n’ in this linear array.
• If search ends in success, it sets ‘ans’ to the index of the element otherwise it sets ‘ans’ to
-1

Code:

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

int linear_search(int ar[], int n, int x)


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

int main()
{
int n;
scanf("%d", &n);

4
int *ar = (int *)malloc(n * sizeof(int));

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


scanf("%d", &ar[i]);

int x;
printf("Enter the no you want to search - ");
scanf("%d", &x);

int index = linear_search(ar, n, x);

if (index == -1)
{
printf("NO NOt FOUND");
}
else
{
printf("the no is found at the index %d", index);
}

return 0;
}

Output

5
Application: To search the presence and absence of an element in an array in O(N) time
complexity.

6
Experiment-2
Write a program to Implement Binary Search in C programming language. Assume the list
is already sorted.

Objective:
To find the desired element in a sorted array or report it’s absence by using Binary Search

Theory:
Binary search is a search algorithm that finds the position of a target value within a sorted array.
Binary search compares the target value to the middle element of the array. Binary search runs in
logarithmic time in the worst case, making O(logn) comparisons , where n is no. of elements in
the array. It is faster than linear search except for small arrays.

Algorithm:
Consider a sorted array -

1. Compare x with mid element.


2. If x matches , return index of x.
3. else , if x is greater than mid , x lies in right half subarray , recur for right.
4. else , if x is smaller than mid , recur for left.

Code:

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

int binary_search(int ar[], int n, int x)


{
int s = 0;
int e = n - 1;

while (s <= e)
{
int mid = (s + e) / 2;

if (ar[mid] == x)
return mid;

else if (ar[mid] > x)


e = mid - 1;

else

7
{
s = mid + 1;
}
}
return -1;
}

int main()
{
int n;
scanf("%d", &n);

int *ar = (int *)malloc(n * sizeof(int));

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


scanf("%d", &ar[i]);

int x;
printf("Enter the no you want to search - ");
scanf("%d", &x);

int index = binary_search(ar, n, x);

if (index == -1)
{
printf("NO NOt FOUND");
}
else
{
printf("the no is found at the index %d", index);
}

return 0;
}

Output

8
Application: Find presence and absence of an element in a sorted array in O(logn) time
complexity.

9
Experiment-3
Write a program to implement the Bubble Sort and also write its applications.

Objective:
To implement Bubble sort algorithm

Theory:
Bubble sort is a simple sorting algorithm. This sorting algorithm is a comparison - based
algorithm in which each pair of adjacent elements is compared and the elements are swapped if
they are not in order. This algorithm is not suitable for large data sets as its average and worst
case complexity are of Ο(n2) where n is the number of items..

Example: -

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:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Algorithm:
1. We take an unsorted array
2. Now compare very first two elements to check which one is greater
3. If second element is greater then they are at right position if second element is smaller
then we will swap the two values.
4. Now we will compare second with third and follow step 3.
5. We will do this till we reaches at end ( last element of array)
6. Our array is sorted.

10
Code:

// C program for implementation of Bubble sort


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

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// A function to implement bubble sort


void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)

// Last i elements are already in place


for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}

/* Function to print an array */


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 n;
printf("Enter number of elements of array : ");
scanf("%d", &n);

printf("Enter array : ");


int *arr = (int *)malloc(n * sizeof(int));

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

bubbleSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

Output

Application:

Bubble sort- Due to its simplicity, bubble sort is often used to introduce the concept of a sorting
algorithm.

In computer graphics it is popular for its capability to detect a very small error (like swap of just
two elements) in almost-sorted arrays and fix it with just linear complexity (2n). For example, it
is used in a polygon filling algorithm, where bounding lines are sorted by their x coordinate at a
specific scan line (a line parallel to x axis) and with incrementing y their order changes (two
elements are swapped) only at intersections of two lines

12
Experiment-4
Write a program to implement the Merge Sort and also write its applications

Objective:
To implement Merge Sort Algorithm.

Theory:
Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides the input array into
two halves, calls itself for the two halves, and then merges the two sorted halves. The merge()
function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that
arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one.

13
Algorithm:
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2

2. Call mergeSort for first half:


Call mergeSort(arr, l, m)

3. Call mergeSort for second half:


Call mergeSort(arr, m+1, r)

4. Merge the two halves sorted in step 2 and 3:


Call merge(arr, l, m, r)

Code:

/* C program for Merge Sort */


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

void merge(int arr[], int s, int e)


{
int mid = (s + e) / 2;
int i = s;
int j = mid + 1;
int k = s;

int temp[1000];

while (i <= mid && j <= e)


{
if (arr[i] < arr[j])
temp[k++] = arr[i++];

else
{
temp[k++] = arr[j++];
}
}

while (i <= mid)


{
temp[k++] = arr[i++];
}
while (j <= e)

14
{
temp[k++] = arr[j++];
}
for (int i = s; i <= e; i++)
{
arr[i] = temp[i];
}
}

void mergeSort(int arr[], int s, int e)


{
if (s < e)
{

int mid = (s + e) / 2;

// Sort first and second halves


mergeSort(arr, s, mid);
mergeSort(arr, mid + 1, e);

merge(arr, s, e);
}
}

/* Function to print an array */


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

/* Driver program to test above functions */


int main()
{
int n;
printf("Enter number of elements of array : ");
scanf("%d", &n);

printf("Enter array : ");


int *arr = (int *)malloc(n * sizeof(int));

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


scanf("%d", &arr[i]);

15
mergeSort(arr, 0, n - 1);

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


printArray(arr, n);
return 0;
}

Output

Applications
1. Merge Sort is useful for sorting linked lists in O(n Log n) time
2. Merge sort can be implemented without extra space for linked lists
3. Merge sort is used for counting inversions in a list
4. Merge sort is used in external sorting

16
Experiment-5
Write a program to insert an element at the mid position in the One-dimensional array.

Objective:
To insert an element at mid position in 1-D array.

Theory:
An array is a collection of items stored at contiguous memory locations. In this Program , we
will learn how to insert an element in an array in C++.
for example, consider an array a[10] having three elements in it initially and a[0] = 1, a[1] = 2
and a[2] = 3 and we want to insert a number 45 at location 4 i.e. a[4] = 45, so we have to move
elements one step .

Algorithm:

1. First get the element to be inserted, say x


2. Then get the iterate till the mid point of array at which this element is to be inserted, say
pos
3. Then shift the array elements from this position to one position forward, and do this for
all the other elements next to pos.
4. Insert the element x now at the position pos, as this is now empty.
Code:

// C Program to Insert an element


// at a middle position in an Array

#include <stdio.h>

int main()
{
int i, x;

int n;
scanf("%d", &n);
int ar[n + 2];

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


{
scanf("%d", &ar[i]);
}

printf("Enter the no you want to insert at the middle: ");


scanf("%d", &x);

17
int pos = (n) / 2;

// shift elements forward


for (i = n; i > pos; i--)
ar[i] = ar[i - 1];

// insert x at pos
ar[pos] = x;

// print the updated array


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

return 0;
}

Output

Applications
1. To shift the elements in an array in various types of problems like array rotation.

18
Experiment-7
Write a program to implement stack data structure and perform its operations.

Objective:
Implement Stack Data Structure.

Theory:
Stack is a linear data structure which follows a particular order in which the operations are
performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Mainly the following three basic operations are performed in the stack:
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.

Pop: Removes an item from the stack. The items are popped in the reversed order in which they
are pushed. If the stack is empty, then it is said to be an Underflow condition.

Peek or Top: Returns top element of stack.

isEmpty: Returns true if stack is empty, else false.

Algorithm:

Implementation of stack using array :


• Include all the header files which are used in the program and define a constant 'SIZE'
with specific value.
• Declare all the functions used in stack implementation.
• Create a one dimensional array with fixed size (int stack[SIZE])
• Define a integer variable 'top' and initialize with '-1'. (int top = -1)

• In main method, display menu with list of operations and make suitable function calls to
perform operation selected by the user on the stack.

Inserting value into the stack (Push Operation)


In a stack, push() is a function used to insert an element into the stack. In a stack, the new element
is always inserted at top position. Push function takes one integer value as parameter and inserts
that value into the stack. We can use the following steps to push an element on to the stack...
• Check whether stack is FULL. (top == SIZE-1)
• If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and terminate
the function.0
• If it is NOT FULL, then increment top value by one (top++) and set stack[top] to value
(stack[top] = value).

Delete a value from the Stack

19
In a stack, pop() is a function used to delete an element from the stack. In a stack, the element is
always deleted from top position. Pop function does not take any value as parameter. We can use
the following steps to pop an element from the stack...
• Check whether stack is EMPTY. (top == -1)
• If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and
terminate the function.
• If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top--).
display() - Displays the elements of a Stack
We can use the following steps to display the elements of a stack...
• Check whether stack is EMPTY. (top == -1)
• If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
• If it is NOT EMPTY, then define a variable 'i' and initialize with top. Display stack[i]
value and decrement i value by one (i--).
• Repeat above step until i value becomes '0'.

Code:

#include <stdio.h>
int stack[100], choice, n, top, x, i;

void push()
{
if (top >= n - 1)
{
printf("\nSTACK is over flow");
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d", &x);
top++;
stack[top] = x;
}
}
void pop()
{
if (top <= -1)
{
printf("\nStack is under flow");
}
else

20
{
printf("\n The popped elements is %d", stack[top]);
top--;
}
}
void display()
{
if (top >= 0)
{
printf("\n The elements in STACK \n");
for (i = top; i >= 0; i--)
printf("\n%d", stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
}

int main()
{
//clrscr();
top = -1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d", &n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t ");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d", &choice);
switch (choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}

21
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf("\n\t Please Enter a Valid Choice(1/2/3/4)");
}
}
} while (choice != 4);
return 0;
}

Output

22
APPLICATIONS:
1. Stacks can be used for expression evaluation.
2. Stacks can be used to check parenthesis matching in an expression.
3. Stacks can be used for Conversion from one form of expression to another.
4. Stacks can be used for Memory Management.
5. Stack data structures are used in backtracking problems.

23
Experiment -7
Write a program to implement two stack using single array.

Objective:
Implement Stack Data Structure.

Theory:
This C Program Implements two Stacks using a Single Array & Check for Overflow &
Underflow. A Stack is a linear data structure in which a data item is inserted and deleted at one
record. A stack is called a Last In First Out (LIFO) structure. Because the data item inserted last
is the data item deleted first from the stack.
To implement two stacks in one array, there can be two methods.

• First is to divide the array in to two equal parts and then give one half two each stack. But
this method wastes space.
• So a better way is to let the two stacks to push elements by comparing tops of each other,
and not up to one half of the array.

Push and Pop functions of both stack in the following code has their Time Complexity as O(1).
They take constant time.
Print is O(n), where n is the number of elements in the stack.

Algorithm:
• Start two stacks from two extreme corners of arr[].
• Stack1 starts from the leftmost element, the first element in stack1 is pushed at index 0.
• The stack2 starts from the rightmost corner, the first element in stack2 is pushed at index
(n-1).
• Both stacks grow (or shrink) in opposite direction.
• To check for overflow,check if there is space between top elements of both stacks.

Code:

/*
* C Program to Implement two Stacks using a Single Array & Check for Overflow & Underfl
ow
*/
#include <stdio.h>
#include <stdlib.h>
#define max 10

int top1, top2, array[max];


void push(void)

24
{
int x, ch;
if (top1 == top2 - 1)
{
printf("stack overflow \n");
return;
}
printf("enter a no \n");
scanf("%d", &x);
printf("\n press 1 to push the element in 1st stack or press 2 for stack 2:");
scanf("%d", &ch);
if (ch == 1)
array[++top1] = x;
else
array[--top2] = x;
printf("%d element is successfully pushed \n", x);
return;
}
void pop(void)
{
int y, ch;
printf("\n press 1 to pop the element from 1st stack or press 2 for from stack 2");
scanf("%d", &ch);
if (ch == 1)
{
if (top1 == -1) // Condition for checking If Stack 1 is Empty
{
printf("stack underflow \n");
return;
}
y = array[top1];
array[top1--]=0;
}
else
{
if (top2 == max) // Condition for checking If Stack 2 is Empty
{
printf("stack underflow \n");
return;
}
y = array[top2];
array[top2++] = 0;
}
printf("%d element is successfully poped from stack \n", y);
return;

25
}
void display(void)
{
int i;
if (top1 == -1)
{
printf("stack 1 is empty \n");
}
else
{

printf("elements of Stack 1 are : \n");


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

int main()
{
int ch;
top1 = -1, top2 = max;

do
{
printf("1:push\n 2:pop\n 3:display\n 4:exit\n choice:");
scanf("%d", &ch);
switch (ch)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:printf("quits from program \n");
break;
default:printf("wrong choice \n");
break;
}
} while (ch != 4);
}

26
Output

27
28
APPLICATIONS:
1. Applications:
2. This method efficiently utilizes the available space.
3. It doesn’t cause an overflow if there is space available in arr[].
4. Space and Memory Optimisation achieved.
5. Time complexity of all 4 operations of twoStack is O(1).

29
Experiment-8
Write a program to find the minimum element of the stack in constant time.

Objective:
To find the minimum element of the stack in constant time

Theory:
Stack is a linear data structure which follows a particular order in which the operations are
performed. The order may be LIFO(Last
We will make an auxiliary stack which stores the minimum element of given stack and
operations on this stack will depend on deletion or insertion of minimum element in given stack.

Algorithm:-
1. Declare two stacks. One is the main stack in which we push value as it is. In the second
stack, we only push the minimum element present at that time.
2. Whenever we perform push operations in a stack.

a) Push the value as it is in a first stack.


b) For the second stack, push only the minimum value. For minimum value, Compare the
current value with the value present at the top of the stack

Code:

#include <stdio.h>

struct Stack
{
int arr1[100], arr2[100];
int top;
};

int main()
{
struct Stack s1;
int n = 1, m, i;

s1.top = -1;
while (n)
{
printf("to push -1, to pop -2, to exit -0 : ");
scanf("%d", &n);
if (n == 1)

30
{
if (s1.top == 100)
{
printf("stack overflow \n");
}
else
{
if (s1.top == -1)
{
printf("enter the number to be pushed : ");
scanf("%d", &m);
s1.arr1[s1.top + 1] = m;
s1.arr2[s1.top + 1] = m;
s1.top++;
}
else
{
printf("enter the number to be pushed : ");
scanf("%d", &m);
s1.arr1[s1.top + 1] = m;
s1.arr2[s1.top + 1] = m;
if (m >= s1.arr2[s1.top])
{
s1.arr2[s1.top + 1] = s1.arr2[s1.top];
}
s1.top++;
}
}
}
else if (n == 2)
{
if (s1.top == 0)
{
printf("stack is empty\n");
}
else
{
s1.top--;
}
}
else if (n == 0)
{
break;
}
printf("the stack is ");

31
for (i = s1.top; i >= 0; i--)
{
printf("%d ", s1.arr1[i]);
}
if (s1.top >= 0 && s1.top < 100)
{
printf("\nthe min. number is %d \n", s1.arr2[s1.top]);
}
}

return 0;
}
Output

APPLICATIONS:

• We will get minimum element in constant time

• Maximum operations of stack will take constant time

32
Experiment-9
Write a program to implement Queue Data structure.

Objective:
Implement Queue Data structure.

Theory:

It is a simple data structure, which has FIFO ( First In First Out) property in which Items are
removed in the same order as they are entered.

QUEUE has two pointer FRONT and REAR, Item can be pushed by REAR End and can be
removed by FRONT End.

Operations on A Queue

• Enqueue- adding an element in the queue if there is space in the queue.


• Dequeue- Removing elements from a queue if there are any elements in the queue
• Front- get the first item from the queue.
• Rear- get the last item from the queue.
• isEmpty/isFull - checks if the queue is empty or full.

Algorithm-

1. Ask the user for the operation like insert, delete, display and exit.

2. According to the option entered, access its respective function using switch statement. Use the
variables front and rear to represent the first and last element of the queue.

3. In the function insert(), firstly check if the queue is full. If it is, then print the output as “Queue
Overflow”. Otherwise take the number to be inserted as input and store it in the variable
add_item. Copy the variable add_item to the array queue_array[] and increment the variable rear
by 1.

4. In the function delete(), firstly check if the queue is empty. If it is, then print the output as
“Queue Underflow”. Otherwise print the first element of the array queue_array[] and decrement
the variable front by 1.

5. In the function display(), using for loop print all the elements of the array starting from front to
rear.

6. Exit.

Code:

#include <stdio.h>

33
#include <stdlib.h>
#define MAX 50
void insert();
void delete ();
void display();
int queue_array[MAX];
int rear = -1;
int front = -1;
void insert()
{
int item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == -1)
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &item);
rear = rear + 1;
queue_array[rear] = item;
printf("\n");
}
}
void delete ()
{
if (front == -1 || front > rear)
{
printf("Queue Underflow \n");
return;
}
else
{
printf("Element deleted from queue is : %d \n", queue_array[front]);
front = front + 1;
}
}
void display()
{
int i;
if (front == -1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");

34
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}
int main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete ();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice n");
}
}
}

Output

35
Applications

• A queue is used in scheduling processes in a CPU.


• It is used in data transfer between processes.
• It holds multiple jobs which are then called when needed.

36
Experiment-10
Write a program to reverse first k elements of a given Queue.

Objective:
To reverse first k elements of a given queue

Theory:

It is a simple data structure, which has FIFO ( First In First Out) property in which Items are
removed in the same order as they are entered. Queue has two pointer FRONT and REAR, Item
can be pushed by REAR End and can be removed by FRONT End.
Given an integer k and a queue of integers, we need to reverse the order of the first k elements of
the queue, leaving the other elements in the same relative order.
Example-Q = [10, 20, 30, 40, 50, 60,70, 80, 90, 100]
k=5
Output : Q = [50, 40, 30, 20, 10, 60,70, 80, 90, 100]
Input : Q = [10, 20, 30, 40, 50, 60,70, 80, 90, 100]
k=4
Output : Q = [40, 30, 20, 10, 50, 60,70, 80, 90, 100]

Code:

#include <stdio.h>

struct queue
{
int arr[100];
int top, bottom;
};

struct stack
{
int arr[100];
int top;
};

int main()
{
struct queue q;
struct stack s;
int n = 1, i, j, m;

37
q.top = -1;
q.bottom = -1;
s.top = -1;
while (n)
{
printf("1-push \n2-pop \n3-reverse \n0-exit : \n ");
scanf("%d", &n);
if (n == 1)
{
if (q.top == -1)
{
q.top = 0;
q.bottom = 0;
printf("Enter the number insert: ");
scanf("%d", &m);
q.arr[q.top] = m;
}
else if (q.bottom == 99)
{
printf("OVERFLOW \n");
}
else
{
printf("Enter the number to insert : ");
scanf("%d", &m);
q.bottom++;
q.arr[q.bottom] = m;
}
}
else if (n == 2)
{
if (q.bottom == -1)
{
printf("Empty queue\n");
}
else
{
q.bottom--;
if (q.bottom == -1)
{

38
q.top = -1;
}
}
}
else if (n == 3)
{
printf("enter the number of elements to be reversed : ");
scanf("%d", &m);
s.top = -1;
for (i = q.top; i < m; i++)
{
s.top++;
s.arr[s.top] = q.arr[i];
}
j = 0;
for (i = s.top; i >= 0; i--)
{
q.arr[j] = s.arr[i];
j++;
}
}
if (q.top == 0)
{
printf("the queue is : ");
for (i = q.top; i <= q.bottom; i++)
{
printf("%d ", q.arr[i]);
}
printf("\n");
}
}
}

Output

39
40
APPLICATIONS:

• To reverse the elements in an queue in various types of problems.

41
Experiment-11
Write a program to check whether given string is Palindrome or not using DEQUEUE.

Objective:
To write a program to check whether a given string is palindrome or not using dequeue.

Theory:
A palindrome is a string that reads the same forward and backward, for example, radar, toot, and
madam. We would construct an algorithm to input a string of characters and check whether it is a
palindrome.
A dequeue data structure is the one in which input is allowed from behind but the elements can
be deleted from both front as well as the rear positions.

ALgorithm:
The solution to this problem will use a deque to store the characters of the string. We will
process the string from left to right and add each character to the rear of the deque. At this point,
the deque will be acting very much like an ordinary queue. However, we can now make use of
the dual functionality of the deque. The front of the deque will hold the first character of the
string and the rear of the deque will hold the last character.

Since we can remove both of them directly, we can compare them and continue only if they
match. If we can keep matching first and the last items, we will eventually either run out of

42
characters or be left with a deque of size 1 depending on whether the length of the original string
was even or odd. In either case, the string must be a palindrome.

Code:

#include<stdio.h>
#include<string.h>
#define MAXSIZE 100
struct dequeue{
char arr[MAXSIZE];
int front;
int rear;
int size;

};

struct dequeue q;

void push(char d){


if(q.size>=MAXSIZE)
printf("Queue is full\n");

else if(q.front==-1){
q.front=0;
q.rear=0;
q.size++;
q.arr[q.rear]=d;

else{
q.rear++;
q.arr[q.rear]=d;
q.size++;

43
char pop_front(){
if(q.size==0){
printf("queue is empty\n");
return '0';
}
else{
char temp = q.arr[q.front];
q.front++;
q.size--;

return temp;
}
}

char pop_back(){
if(q.size==0){
printf("queue is empty\n");
return '0';
}
else{
char temp = q.arr[q.rear];
q.rear--;
q.size--;

return temp;
}
}

int isPalindrome(){
while(q.rear>q.front){

if(pop_back()!=pop_front())
return 0;
}
return 1;

int main(){

44
char ch[10];
q.front=-1;
q.rear=-1;
q.size=0;
printf("Enter string: ");
scanf("%s",ch);

for(int i=0;ch[i]!='\0';i++){
push(ch[i]);
}
int c= isPalindrome();

if(c==1)
printf("\nIt is a palindrome");
else
printf("\nIt is not a palindrome");
return 0;
}

Output

45
APPLICATIONS:
1. To Check whether the string is a palindrome or not and various other problems. Stacks
can be used for Memory Management.
2. Stack data structures are used in backtracking problems.

46
Experiment-12
Implement Tower of Hanoi using stack data structure.

Objective:
To implement tower of hanoi using stack data structure.

Theory:
Tower of Hanoi is a mathematical puzzle. It consists of three poles and a number of disks of

different sizes which can slide onto any poles. The puzzle starts with the disk in a neat stack in

ascending order of size in one pole, the smallest at the top thus making a conical shape. The

objective of the puzzle is to move all the disks from one pole (say ‘source pole’) to another pole

(say ‘destination pole’) with the help of the third pole (say auxiliary pole).

The puzzle has the following two rules:

1. You can’t place a larger disk onto smaller disk

2. Only one disk can be moved at a time

Algorithm:
1. Calculate the total number of moves required i.e. "2n - 1"

here n is the number of disks.

2.If number of disks (i.e. n) is even then interchange destination

pole and auxiliary pole.

3. for i = 1 to total number of moves:

if i%3 == 1:

legal movement of top disk between source pole and

destination pole

if i%3 == 2:

legal movement top disk between source pole and

47
auxiliary pole

if i%3 == 0:

legal movement top disk between auxiliary pole


and destination pole

Code:

#include<stdio.h>
#include<math.h>
#define MAXSIZE 100

struct stack{
int top;
int arr[MAXSIZE];
};

int isfull(struct stack s){


if(s.top == MAXSIZE-1){
// printf("Stack is full");
return 1;
}
return 0;
}

int isEmpty(struct stack s){


if(s.top == -1){
// printf("stack is empty");
return 1;
}
return 0;
}
void push(struct stack s, int data){
if(isfull(s)){
return;
}
s.top++;
s.arr[s.top] = data;
}

int pop(struct stack s){


if(isEmpty(s)){
return 0;

48
}

int temp = s.arr[s.top];


s.top--;
return temp;
}

void move(char src, char dest, int disk_no){


printf("Move the disk %d from %c to %c\n", disk_no, src, dest );

void move_disk(struct stack src, struct stack dest, char s, char d ){


int src_top = pop(src);
int dest_top = pop(dest);

if(src_top == 0){
push(src, dest_top);
move(d, s, dest_top);
}

else if(dest_top == 0){


push(dest, src_top);
move(s, d, src_top);
}

else if(src_top > dest_top){


push(src, src_top);
push(src, dest_top);
move(d,s, dest_top);
}
}

void solve(int n, struct stack src, struct stack helper, struct stack dest){

int i , count_moves;
char s = 'A',d = 'B', h = 'C';

if(n %2 == 0){
char temp = d;
d = h;
h = temp;

49
}
count_moves = pow(2, n) -1;

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


push(src, i);
// printf("sdfa");
}

for(int i = 1;i<= count_moves;i++){


if(i%3 == 1)
move_disk(src, dest, s, d);
else if(i%3 == 2)
move_disk(src, helper, s, h);
else if(i%3 == 0)
move_disk(helper, dest, h, d);
}

int main(){

struct stack src, dest, helper;


src.top = -1;
dest.top = -1;
helper.top = -1;
int n;
scanf("%d", &n);

solve(n, src, helper, dest);

return 0;
}

Output

50
APPLICATIONS:
To solve the famous Tower of Hanoi puzzle for any number of discs iteratively.

51
Experiment-13
Write a program to find Nearest Smaller Element using the queue data structure

Objective:
To find the nearest minimum element on the left side of an element

Theory:
We are using Deque data structure to find the nearest minimum element on the left side of an
element , deque structure supports push and pop on both sides of an array .

Algorithm-
1. Create an empty deque of type int
2. Take the no of elements from the user and store in n
3.Take n elements and store them in array
4.Create a queue to store the final ans for each element
5.Initialize variable i with 0
6. Run a while loop , until the back element of deque is smaller then the current element in the
array (a[i]), or until the deque is empty
7. If deque is empty push (-1) for that element into queue it means there is no smaller element on
the left side of that element(a[i])
8. If deque is not empty push the back element of deque in the queue
9.Push the current element of array(a[i]) into deque
10.Increment the value of i to i+1
11.Repeat steps 6-10 until i reaches to n
12. Pop the element from queue and print the nearest minimum element for each element in the
input

Code:

#include <iostream>
#include <deque>

using namespace std;

void nearest_smaller(int arr[], int n)


{
deque<int> q;

int *ans = new int[n];


ans[0] = -1;
q.push_back(arr[0]);
for (int i = 1; i < n; i++)
{

while (!q.empty() && q.back() > arr[i])

52
{
q.pop_back();
}
if (q.empty())
ans[i] = -1;
else
ans[i] = q.back();
q.push_back(arr[i]);
}
cout << "array printing the nearest element is ";
for (int i = 0; i < n; i++)
cout << ans[i] << ",";
}

int main()
{

int n;
cout << "Enter the no of elements in the array ";
cin >> n;
int *arr = new int[n];
cout << "Enter array ";
for (int i = 0; i < n; i++)
cin >> arr[i];

nearest_smaller(arr, n);

return 0;
}

Output

53
APPLICATIONS:
1. Since Deque supports both stack and queue operations, it can be used as both. The
Deque data structure supports clockwise and anticlockwise rotations in O(1) time which
can be useful in certain applications.
2. The problems where elements need to be removed and or added both ends can be
efficiently solved using Deque.

54
Experiment-14
Given a Sorted doubly linked list of positive integers and an integer, then finds all the pairs
(sum of two nodes data part) that are equal to the given integer value. Example: Double
Linked List 2, 5, 7, 8, 9, 10, 12, 16, 19, 25, and P=35 then pairs will be Pairs will be (10, 25),
(16, 19).

Objective:
Implement Stack Data Structure.

Theory:
A Doubly linked list is a linked list that consists of a set of sequentially linked records called
nodes. Each node contains two fields that are references to the previous and to the next node in
the sequence of node.
A simple approach for this problem is to one by one pick each node and find the second element
whose sum is equal to x in the remaining list by traversing in forward direction. Time complexity
for this problem will be O(n^2), n is the total number of nodes in the doubly linked list.
Algorithm
• Initialize two pointer variables to find the candidate elements in the sorted doubly linked
list. Initialize first with start of doubly linked list i.e.; first=head and initialize second with
last node of doubly linked list i.e.; second=last node.
• We initialize first and second pointers as first and last nodes. Here we don’t have random
access, so to find a second pointer, we traverse the list to initialize the second.
• If the current sum of first and second is less than x, then we move first in forward
direction. If the current sum of first and second element is greater than x, then we move
second in backward direction.
• Loop termination conditions are also different from arrays. The loop terminates when
either of two pointers become NULL, or they cross each other (second->next = first), or
they become same (first == second)
Code:

#include <iostream>
using namespace std;
class Node{
public:
int data;
Node*prev;
Node*next;
Node(int d){
data = d;
prev = next = NULL;
}
};
void Insert(Node *&front, Node *&rear, int d){
if(front == NULL){
front = new Node(d);

55
rear = front;
return;
}
Node *newNode = new Node(d);
rear->prev = newNode;
newNode->next = rear;
rear = newNode;
}
void build(Node *&front, Node *&rear){
int n,d;
// cout<<"How many elements do you want in the linked list : ";
cin>>n;
// cout<<"Enter the elements of the linked list(in sorted order) : ";
for(int i=0; i<n; i++){
cin>>d;
Insert(front,rear,d);
}
}
void findPairs(Node *front, Node *rear, int m){
if(front == NULL){
return;
}
cout<<"Pairs are \n";
while((rear != front) && (rear->prev != front)){
if(front->data + rear->data == m){
cout<<"("<<front->data<<","<<rear->data<<")\n";
front = front->prev;
rear = rear->next;
}
else if(front->data + rear->data > m){
rear = rear->next;
}
else{
front = front->prev;
}
}
}
int main()
{
int m;
Node *front = NULL;
Node *rear = NULL;
build(front,rear);
// cout<<"Enter m : ";
cin>>m;

56
findPairs(front,rear,m);
return 0;
}

Output

APPLICATIONS:
• Doubly linked lists can be used in navigation systems where both front and back navigation
is required.
• It is used by browsers to implement backward and forward navigation of visited web pages
i.e. back and forward buttons.
• It is also used by various applications to implement Undo and Redo functionality.
• It can also be used to represent a deck of cards in games.

57
Experiment-15
Write a program to find the middle element of the given linked list in a single pass.

Theory:
A linked list is a sequence of data structures, which are connected together via links.
Linked List is a sequence of links which contains items. Each link contains a connection to
another link. Linked list is the second most-used data structure after array.

Algorithm :

1) Traverse linked list using two pointers.


2) Move one pointer by one and the other pointers by two.
3) When the fast pointer reaches the end slow pointer will reach the middle of the linked list.

Code:

#include <iostream>

using namespace std;

class node
{
public:
int data;
node *next;

node(int d)
{
data = d;
next = NULL;
}
};

class linked_list
{
node *head, *tail;

public:
linked_list()
{
head = NULL;
tail = NULL;
}

58
void insert(int d)
{
if (head == NULL)
{
head = new node(d);
head->next = tail;
tail = head;
tail->next = NULL;
return;
}
node *temp = new node(d);
tail->next = temp;
tail = tail->next;
}

void print()
{
node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ->";
temp = temp->next;
}
cout << endl;
}

void middle()
{
if (head == NULL or head->next == NULL)
return;

node *slow = head;


node *fast = head->next;

while (fast != NULL and fast->next != NULL)


{
fast = fast->next->next;
slow = slow->next;
}

cout<<slow->data<<endl;
}
};

int main()

59
{
linked_list l;
int n;
cout<<"how many elements you want to enter: ";
cin>>n;
for(int i=0;i<n;i++){
int d;
cin>>d;
l.insert(d);
}
cout<<"Linked list is: ";
l.print();
cout<<"middle element in the list is: ";
l.middle();

return 0;
}

Output

60
Experiment-16
Write a program to check whether given tree is binary search tree or not.

Theory:
Binary Search Tree is a node-based binary tree data structure which has the following properties:
The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
Algorithm:
• To see if a binary tree is a binary search tree, check:
• If a node is a left child, then its key and the keys of the nodes in its right subtree are less than
its parent’s key.
• If a node is a right child, then its key and the keys of the nodes in its left subtree are greater
than its parent’s key.

Code:

#include <bits/stdc++.h>
#include<climits>

using namespace std;

class node{
public:
int data;
node* left;
node* right;

node(int data){
this->data = data;
this->left = NULL;
this->right =NULL;
}
};

node* buildTree(node*root){
int data;
cin>>data;

if(data==-1){
return NULL;
}

61
if(root==NULL){
node* n = new node(data);
root = n;
}

root->left = buildTree(root->left);
root->right = buildTree(root->right);

return root;
}

void displayPreorder(node*root){ //NLR


if(root==NULL){
return;
}

cout<<root->data<<" ";
displayPreorder(root->left);
displayPreorder(root->right);
}

bool isBST(node* root,int minrange=INT_MIN,int maxrange=INT_MAX)


{
if(root==NULL)
return true;

bool leftBST = isBST(root->left,minrange,root->data);


bool rightBST = isBST(root->right,root->data,maxrange);
if(rightBST & leftBST & root->data < maxrange & root->data > minrange)
{
return true;
}
else
return false;
}

int main()
{

node* root = NULL;


root = buildTree(root);
displayPreorder(root);
cout<<endl;
if(isBST(root))
cout<<"It is a BST\n";

62
else
cout<<"It is not a BST\n";

return 0;
}

Output

APPLICATIONS:
1. used to efficiently store data in sorted form in order to access and search stored
elements quickly.
2. They can be used to represent arithmetic expressions (Refer here for more info )
3.BST used in Unix kernels for managing a set of virtual memory areas.

63
Experiment-17
Write a program to implement insertion in AVL tree.

Objective:
To implement AVL Trees.

Theory:
AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of
left and right subtrees cannot be more than one for all nodes.
Example of an AVL Tree

The above tree is AVL because differences between heights of left and right subtrees for every
node is less than or equal to 1.

Algorithm:
Step 1:Insert the node in the AVL tree using the same insertion algorithm of BST.
Step 2:Once the node is added, the balance factor of each node is updated.
Step 3:Now check if any node violates the range of the balance factor if the balance factor is
violated, then perform rotations using the below case.
If BF(node) = +2 and BF(node -> left-child) = +1, perform LL rotation.
If BF(node) = -2 and BF(node -> right-child) = 1, perform RR rotation.
If BF(node) = -2 and BF(node -> right-child) = +1, perform RL rotation.
If BF(node) = +2 and BF(node -> left-child) = -1, perform LR rotation.

Code:

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

class Node{
public:
int value;
Node *left;
Node *right;
int height;
Node(int d){
value = d;
left = right = NULL;
height = 1;
}
};

64
int getHeight(Node *node){
if(node == NULL){
return 0;
}
return node->height;
}
int getBalanceFactor(Node *node){
if(node == NULL){
return 0;
}
return getHeight(node->left) - getHeight(node->right);
}
Node *RightRotation(Node *node)
{
Node *x = node->left;
Node *y = x->right;
x->right = node;
node->left = y;
node->height = max(getHeight(node->left),
getHeight(node->right)) + 1;
x->height = max(getHeight(x->left),
getHeight(x->right)) + 1;
return x;
}
Node *LeftRotation(Node *node)
{
Node *x = node->right;
Node *y = x->left;
x->left = node;
node->right = y;
node->height = max(getHeight(node->left),
getHeight(node->right)) + 1;
x->height = max(getHeight(x->left),
getHeight(x->right)) + 1;
return x;
}
Node* buildAVL(Node* node, int d){
if(!node){
Node* New = new Node(d);
return New;
}
if(node->value < d){
node->right = buildAVL(node->right,d);
}
else if(node->value > d){

65
node->left = buildAVL(node->left,d);
}
else{
return node;
}
node->height = 1 + max(getHeight(node->left),getHeight(node->right));

int balanceFact = getBalanceFactor(node);


if(balanceFact >1 && node->left->value > d){
return RightRotation(node);
}
if(balanceFact < -1 && d > node->right->value)
return LeftRotation(node);
if(balanceFact < -1 && d < node->right->value){
node->right = RightRotation(node->right);
return LeftRotation(node);
}
if(balanceFact > 1 && d > node->left->value){
node->left = LeftRotation(node->left);
return RightRotation(node);
}

return node;
}
void InOrderPrint(Node*node)
{
if(node==NULL)
return;
InOrderPrint(node->left);
cout<<node->value<<" ";
InOrderPrint(node->right);
}
int main()
{
Node *node = NULL;
node = buildAVL(node,14);
node = buildAVL(node,6);
node = buildAVL(node,15);
node = buildAVL(node,12);
node = buildAVL(node,2);
node = buildAVL(node,3);
node = buildAVL(node,30);
node = buildAVL(node,15);
cout<<"Inorder traversal(sorted) of the AVL tree :\n";
InOrderPrint(node);

66
return 0;

Output

APPLICATIONS:
• There are few insertion and deletion operations
• Short search time is needed
• Input data is sorted or nearly sorted

67
Experiment-18
Write a program to print spiral order of a Binary Tree.

Objective:
To print spiral order of Binary Tree.

Theory:
In level order traversal we make use of a single queue while in spiral order traversal we need use
two stacks. First stack('stackEven') is used to traverse the nodes at even level and second
stack('stackOdd') is used to traverse the nodes at odd level. Nodes at even level are stored in
'stackEven' and are pushed in it from left to right order whereas nodes at odd level are stored in
'stackOdd' and are pushed in it from right to left order.

Output: 0 1 2 6 3 5 4 7 8 9

Algorithm:

1. Push root node into the 'stackEven'. Set boolean 'evenLevel' to true. This boolean variable is
used to indicate if the current level being visited is even level or odd level.

2. Now if 'evenLevel' is set to true repeat steps 2a to 2c until 'stackEven' is not empty.
2a. Pop the node from 'stackEven'. Let popped node be 'currentNode'. Print the value of
'currentNode'.
2b. If the right child of 'currentNode' is not null, push it into the 'stackOdd'.
2c. If the left child of 'currentNode' is not null, push it into the 'stackOdd'.
Notice that currentNode's right child is pushed first and then its left child is pushed.

3. If 'evenLevel' is not set to true then repeat steps 3a to 3c until 'stackOdd' is not empty.

68
3a. Pop the node from 'stackOdd'. Let popped node be 'currentNode'. Print the value of
'currentNode'.
3b. If the left child of 'currentNode' is not null, push it into the 'stackEven'.
3c. If the right child of 'currentNode' is not null, push it into the 'stackEven'.
Notice that currentNode's left child is pushed first and then its right child is pushed.

4. If 'evenLevel' is true set it to false and if it is false set it to true. This is because the next level
visited would be odd if current level is even and vice versa.

5. Repeat steps 2-4 until both 'stackEven' and 'stackOdd' are not empty.

Code:

#include <bits/stdc++.h>
using namespace std;
class Treenode
{
public:
int data;
Treenode *left;
Treenode *right;
Treenode(int d)
{
data = d;
left = right = NULL;
}
};
Treenode *buildTree()
{
cout << "Enter level order input for the binary tree ";
Treenode *root;
int d, l, r;
cin >> d;
queue<Treenode *> q;
root = new Treenode(d);
q.push(root);
while (!q.empty())
{
Treenode *t = q.front();
q.pop();
cin >> l >> r;
if (l != -1)
{
t->left = new Treenode(l);

69
q.push(t->left);
}
if (r != -1)
{
t->right = new Treenode(r);
q.push(t->right);
}
}
return root;
}
void spiral_order(Treenode *root, int lvl, map<int, vector<int>> &m)
{
if (!root)
{
return;
}
m[lvl].push_back(root->data);
spiral_order(root->left, lvl + 1, m);
spiral_order(root->right, lvl + 1, m);
}
vector<int> findSpiral(Treenode *root)
{
map<int, vector<int>> m;
spiral_order(root, 0, m);
vector<int> ans;
for (auto p : m)
{
if (p.first == 0 || p.first % 2 == 0)
{
for (int i = p.second.size() - 1; i >= 0; i--)
{
ans.push_back(p.second[i]);
}
}
else
{
for (int i = 0; i < p.second.size(); i++)
{
ans.push_back(p.second[i]);
}
}
}
return ans;
}

70
int main()
{
Treenode *root = buildTree();
vector<int> v = findSpiral(root);
cout << "Spiral order print of binary tree\n";
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << " ";
}
return 0;
}

Output

APPLICATIONS:

1. Help in understanding concepts of Binary Tree.


2. Study use of stack and queue.
3. Concept of classes and structures.

71
Experiment-19
Write a program to print the left view of a Binary Tree.

Objective:
To print the left view of the Binary Tree.

Theory:
The left view contains all nodes that are first nodes in their levels. A simple solution is to do
level order traversal and print the first node in every level.

The problem can also be solved using simple recursive traversal. We can keep track of the level
of a node by passing a parameter to all recursive calls. The idea is to keep track of the maximum
level also. Whenever we see a node whose level is more than the maximum level so far, we print
the node because this is the first node in its level.We traverse the left subtree before the right
subtree.

Algorithm:

1. Initialize maxlevel to 0 and call leftview(currentNode = root,

level = 1,maxlevel=0)

2. In function leftview(currentNode, level),

a. If currentNode is null, then we do nothing and return.

b. Else, if (level > maxLevel) we print out the currentNode's value and update maxLevel to
level.

72
c. Make a recursive call leftview(currentNode.left, level + 1,maxlevel) to make sure nodes in
the left subtree are visited.

d. Make a recursive call leftview(currentNode.right, level + 1,maxlevel) to make sure nodes in


the right subtree are visited.

Code:

#include <bits/stdc++.h>

using namespace std;


#define val INT_MIN
vector<int> v;
class Treenode
{
public:
int data;
Treenode *left;
Treenode *right;
Treenode(int d)
{
data = d;
left = NULL;
right = NULL;
}
};
Treenode *BuildLevelWise()
{
int d;
cin >> d;
Treenode *root = new Treenode(d);
queue<Treenode *> q;
q.push(root);
while (!q.empty())
{
Treenode *t = q.front();
q.pop();
int l, r;
cin >> l >> r;
if (l != -1)
{
t->left = new Treenode(l);
q.push(t->left);
}
if (r != -1)

73
{
t->right = new Treenode(r);
q.push(t->right);
}
}
return root;
}
void BFS(Treenode *root)
{
queue<Treenode *> q;
q.push(root);
q.push(NULL);
while (!q.empty())
{
Treenode *t = q.front();
if (t != NULL)
{
//cout<<f->data<<" ";
v.push_back(t->data);
q.pop();
if (t->left)
q.push(t->left);
if (t->right)
q.push(t->right);
}
else
{
//cout<<"\n";
v.push_back(val);
q.pop();
if (!q.empty())
q.push(NULL);
}
}
cout << v[0] << " ";
for (int i = 1; i < v.size(); i++)
{
if (v[i] == val && i != v.size() - 1)
cout << v[i + 1] << " ";
}
}
int main()
{
cout << "Enter Level order input for the binary tree : ";
Treenode *root = BuildLevelWise();

74
cout << "\nLeft view : \n";
BFS(root);
return 0;
}

Output

APPLICATIONS:
1. Help in understanding concepts of Binary Tree.
2. Study use of stack and queue.
3. Concept of classes and structures.

75
76

You might also like