Encrypted Data Structures.

Download as pdf or txt
Download as pdf or txt
You are on page 1of 120

KRISHNA INSTITUTE OF TECHNOLOGY

DATA STRUCTURE
(RCS-305)
B.Tech. 2ND Year

Ruchi Khetan
(Computer Science Dept.)
KRISHNA INSTITUTE OF TECHNOLOGY

RCS-305 DATA STRUCTURE

TOPICS NO. OF
UNIT QUESTIONS

Introduction: Basic Terminology, Elementary Data Organization, Algorithm,


Efficiency of an Algorithm, Time and Space Complexity, Asymptotic
Unit-1 notations: Big-Oh, Time-Space tradeoff. Abstract Data Types (ADT), Arrays: 31
Definition, Single and Multidimensional Arrays, Representation of Arrays:
Row Major Order, and Column Major Order, Application of arrays, Sparse
Matrices and their representations. Linked lists: Array Implementation and
Dynamic Implementation of Singly Linked Lists, Doubly Linked List,
Circularly Linked List, Operations on a Linked List. Insertion, Deletion,
Traversal, Polynomial Representation and Addition, Generalized Linked List.

Stacks: Abstract Data Type, Primitive Stack operations: Push & Pop, Array
and Linked Implementation of Stack in C, Application of stack: Prefix and
Unit-2 Postfix Expressions, Evaluation of postfix expression, Recursion, Tower of 30
Hanoi Problem, Simulating Recursion, Principles of recursion, Tail recursion,
Removal of recursion Queues, Operations on Queue: Create, Add, Delete, Full
and Empty, Circular queues, Array and linked implementation of queues in C,
Dequeue and Priority Queue.

Trees: Basic terminology, Binary Trees, Binary Tree Representation: Array


Representation and Dynamic Representation, Complete Binary Tree,
Unit-3 Algebraic Expressions, Extended Binary Trees, Array and Linked 19
Representation of Binary trees, Tree Traversal algorithms: Inorder, Preorder
and Postorder, Threaded Binary trees, Traversing Threaded Binary trees,
Huffman algorithm.
Graphs: Terminology, Sequential and linked Representations of Graphs:
Adjacency Matrices, Adjacency List, Adjacency Multi list, Graph Traversal :
Depth First Search and Breadth First Search, Connected Component, Spanning
Unit-4 Trees, Minimum Cost Spanning Trees: Prims and Kruskal algorithm. 11
Transitive Closure and Shortest Path algorithm: Warshal Algorithm and
Dijikstra Algorithm, Introduction to Activity Networks.
Searching: Sequential search, Binary Search, Comparison and Analysis
Internal Sorting: Insertion Sort, Selection, Bubble Sort, Quick Sort, Two Way
Merge Sort, Heap Sort, Radix Sort, Practical consideration for Internal Sorting.
Unit-5 Search Trees: Binary Search Trees (BST), Insertion and Deletion in BST, 31
Complexity of Search Algorithm, AVL trees, Introduction to m-way Search
Trees, B Trees & B+ Trees . Hashing: Hash Function, Collision Resolution
Strategies. Storage Management: Garbage Collection and Compaction.
KRISHNA INSTITUTE OF TECHNOLOGY

UNIT-1
 Introduction: Basic Terminology Elementary Data Organization
 Algorithm, Efficiency of an Algorithm
 Time and Space Complexity
 Asymptotic notations: Big-Oh
 Abstract Data Types (ADT)
 Arrays: Definition, Single and Multidimensional Arrays
 Representation of Arrays: Row Major Order, and Column Major Order
 Application of arrays
 Sparse Matrices and their representations
 Linked lists: Array Implementation and Dynamic Implementation of Singly
Linked Lists
 Doubly Linked List
 Circularly Linked List
 Operations on a Linked List: Insertion, Deletion, Traversal
 Polynomial Representation

Page 1
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.1 What is data type?

Ans. A Data type refers to a named group of data which share similar properties or characteristics
and which have common behavior among them. Three fundamental data types used in C
programming are int for integer values, float for floating-point numbers and char for character
values.

Q.2 What is data structure?


Ans. A Data structure is a named group of data of different data types which can be processed as
a single unit.

or
Data structure is representation of the logical relationship existing between individual elements
of data. In other words, a Data structure is a way of organizing all data items that considers not
only the elements stored but also their relationship to each other.

or
Data structures are the building blocks of a program. And hence the selection of particular data
structure stresses on the following two things :

1. The data structures must be rich enough in structure to reflect the relationship existing
between the data.

2. And the structure should be simple so that we can process data effectively whenever
required.

Q.3 What is an algorithm?

Ans. An algorithm is a step-by-step procedure to solve a particular function i.e., it is a set of


instructions written to carry out certain tasks and the data structure is the way of organizing the
data with their logical relationship maintained.

Q.4 Give the classification of data structure in brief.


Ans. Data structures are normally divided into two broad categories.

 Primitive Data Structures(built-in)

 Non-Primitive Data Structures(user defined)

Q.5 What is primitive data structure?

Ans. These are basic structures and are directly operated upon by the machine instructions. These,
in general, have different representations on different computers. Integers, floating-point
numbers, character constants, string constants, pointers etc. fall in this category.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 2
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.6 What is non primitive data structure?

Ans. These are more complicated data structures. These are derived from the primitive data
structures. The non-primitive data structures emphasize on structuring of a group of homogeneous
(same type) or heterogeneous (different type) data items. Arrays, structures, lists and files are
examples.
The data appearing in our data structures are processed by means of certain operations. In fact, the
particular data structure that one chooses for a given situation depends largely on the frequency
with which specific operations are performed.

Q. 7 Draw the block diagram for the classification of data structure.


Ans.

Q.8 Write down the different operation of data structure.

Ans. The basic operations that are performed on data structures are as follows :
1. Traversing : Accessing each record exactly once so that certain items in the record may be
processed. (This accessing and processing is sometimes called “visiting” the record).

2. Searching : Searching operation finds the presence of the desired data item in the list of
data item. It may also find the locations of all elements that satisfy certain conditions.
3. Inserting : Inserting means addition of a new data element in a data structure.
4. Deleting : Deleting means removal of a data element from a data structure.

The following two operations, which are used in special situations, will also be considered:
(1) Sorting : Sorting is the process of arranging all data items in a data structure in a
particular order say for example, either in ascending order or in descending order.
(2) Merging : Combining the records of two different sorted files into a single sorted file.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 3
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.9 State the difference between array and link list.

Ans.

BASIS FOR
ARRAY LINKED LIST
COMPARISON

Basic It is a consistent set of a fixed It is an ordered set comprising a variable


number of data items. number of data items.

Size Specified during declaration. No need to specify; grow and shrink


during execution.

Storage Allocation Element location is allocated during Element position is assigned during run
compile time. time.

Order of the elements Stored consecutively Stored randomly

Accessing the element Direct or randomly accessed, i.e., Sequentially accessed, i.e., Traverse
Specify the array index or starting from the first node in the list by
subscript. the pointer.

Insertion and deletion Slow relatively as shifting is Easier, fast and efficient.
of element required.

Searching Binary search and linear search linear search

Memory required less More

Memory Utilization Ineffective Efficient

Q.10 Explain the term time and space complexity?

Ans. Complexity of algorithm is a function of size of input of a given problem instance which
determines how much running time/memory space is needed by the algorithm in order to run to
completion.

Time Complexity: Time complexity of an algorithm is the amount of time it needs in order to run
to completion.

Space Complexity: Space Complexity of an algorithm is the amount of space it needs in order to
run to completion.
There are two points which we should consider about computer programming:-
An appropriate data structure
An appropriate algorithm.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 4
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.11 Explain Asymptotic Big- Oh notation?

Ans. Big-Oh Notation (O):

It provides possibly asymptotically tight upper bound for f(n) and it does not give best case
complexity but can give worst case complexity.

Let f be a nonnegative function. Then we define the three most common asymptotic bounds as
follows.

We say that f(n) is Big-O of g(n), written as f(n) = O(g(n)), iff there are positive constants c and
n0 such that

0 ≤ f(n) ≤ c g(n) for all n ≥ n0

If f(n) = O(g(n)), we say that g(n) is an upper bound on f(n).

Q.13 Explain Asymptotic Big- Omega notation?

Ans. Big-Omega Notation (Ω):


It provides possibly asymptotically tight lower bound for f(n) and it does not give worst case
complexity but can give best case complexity

f(n) is said to be Big-Omega of g(n), written as f(n) = Ω(g(n)), iff there are positive constants c
and n0 such that

0 ≤ c g(n) ≤ f(n) for all n ≥ n0

If f(n) = Ω(g(n)), we say that g(n) is a lower bound on f(n).

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 5
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.14 Explain Asymptotic Big- Theta notation?

Ans. We say that f(n) is Big-Theta of g(n), written as f(n) = Θ(g(n)), iff there are positive
constants c1, c2 and n0 such that

0 ≤ c1 g(n) ≤ f(n) ≤ c2 g(n) for all n ≥ n0

Equivalently, f(n) = Θ(g(n)) if and only if f(n) = O(g(n)) and f(n) = Ω(g(n)). If f(n) = Θ(g(n)), we
say that g(n) is a tight bound on f(n).

Q.15 What is an array ?

Ans. An array is defined as a set of finite number of homogeneous elements or data items. It
means an array can contain one type of data only, either all integers, all floating-point numbers, or
all characters. Declaration of arrays is as follows :
INT A[10];

where int specifies the data type or type of elements array stores. “A” is the name of the array,
and the number specified inside the square brackets is the number of elements an array can store,
this is also called size or length of array.

Some important concepts of arrays are :


(1) The individual element of an array can be accessed by specifying name of the array,
followed by index or subscript (which is an integer number specifying the location of
element in the array) inside square brackets. For example to access the fifth element of array
a, we have to give the following statement :
A[4];
(2) The first element of the array has index zero [0]. It means the first element and last element
of the above array will be specified as :
A[0], and A[9] respectively.

(3) The elements of array will always be stored in consecutive memory locations.

(4) The number of elements that can be stored in an array i.e., the size of array or its length is
given by the following equation :
(upperbound – lowerbound) + 1

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 6
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

For the above array, it would be (9-0) + 1 = 10. Where 0 is the lower bound of array, and 9
is the upper bound of array.

(5) Arrays can always be read or written through loop. If we read a one-dimensional array, it
requires one loop for reading and other for writing (printing) the array. For example :

(a) For reading the array


for ( i = 0; i < = 9 ; i++)
{
scanf(“%d”, & A [ i ] );
}

(b) For writing the array


for ( i = 0; i < = 9 ; i++)
{
printf(“%d ”, A [ i ] );
}

If we are reading or writing two-dimensional array it would require two loops. And similarly the
array of n dimension would required n loops.

Some common operations performed on arrays are :

1. Creation of an array.
2. Traversing an array (accessing array elements).
3. Insertion of new elements.
4. Deletion of required element.
5. Modification of an element.
6. Merging of arrays.

Q.16 Define Link List?

Ans. A linked list is a linear collection of data elements, called node pointing to the next nodes by
means of pointers.
Each node is divided into two parts : the first part containing the information of the element, and
the second part called the link or next pointer containing the address of the next node in the list.
Technically, each such element is referred to as a node, therefore a list can be defined as a
collection of nodes as shown in Fig. below :
START (START stores the address of first node)

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 7
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.17 Explain Stack?


Ans. A stack is a non-primitive linear data structure.
 It is an ordered list in which addition of new data item and deletion of already existing data
item is done from only one end, known as Top of Stack (TOS).
 As all the deletion and insertion in a stack is done from top of the stack, the last added
element will be the first to be removed from the stack.
 The stack is also called Last-In-First-Out (LIFO) type of list. Consider some examples,

Eg. A common model of a stack is plates in a marriage party. Fresh plates are “pushed” onto the
top and “popped” off the top.

Q.18 Define Queue?

Ans. Queue is a linear data structure that permits insertion of an element at one end and deletion
of an element at the other end.

 The end at which the deletion of an element take place is called front, and the end at
which insertion of a new element can take place is called rear.
 The deletion or insertion of elements can take place only at the front and rear end of the
list respectively.
 The first element that gets added into the queue is the first one to get removed from the
list.
 Queue is also referred to as First-In-First-Out (FIFO) list. .

Fig. shows the pictorial representation of a Queue.

10 20 30 40 50 60 70 80

Front Rear

In Fig, 10 is the first element and 80 is the last element added to the Queue. Similarly, 10 would
be the first element to get removed and 80 would be the last element to get removed.

Q.19 Explain Tree Data Structure.


Ans. A Tree can be defined as a finite set of data items (nodes). Tree is a non-linear type of data
structure in which data items are arranged of stored in a sorted sequence. Trees represent the
hierarchical relationship between various elements. In trees :

1. There is a special data item at the top of hierarchy called the Root of the Tree.

2. The remaining data items are partitioned into number of mutually exclusive (i.e. disjoint)
subsets, each of which is itself, a tree, which is called the subtree.

3. The tree always grows in length towards bottom in data structures, unlike natural trees which
grows upwards.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 8
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

The tree structure organizes the data into branches, which relate the information. A tree is shown
in Fig.

Q.20 Define array and the type of array ?


Ans. “An array is a collection of variables of the same type that are referenced by a common
name.”

Arrays are a way to group a number of items into a larger unit. In C, array elements are stored in
contiguous (consecutive) memory locations. The lowest address corresponds to the first element
and the highest address to the last element. Arrays can have data items of simple types like int or
float or even of user-defined types like structure or objects.

Types of Arrays
Arrays are of different types:
1. Single-dimensional arrays, comprised of finite homogenous(same type) elements.

2. Multi-dimensional arrays, comprised of elements, each of which is itself an array. A two


dimensional array is the simplest of the multi-dimensional arrays. However, C programming
allows arrays of more than two dimensions. The exact limit (of dimensions), if any, is
determined by the compiler you use.

Q.21 Explain in detail single dimensional array?


Ans. The simplest form of an array is the single-dimensional array.
 The array is given a name and its elements are referred to by their subscripts or indices.
 C language array‟s index numbering starts with zero.
 The index of first element is known as lower bound and the index of the last element is
known as upper bound.

 Declaration of Single-dimensional array :

data_type array-name[size];

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 9
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

where data_type declares the base type of array, which is the type of each element in the array.
The array-name specifies the name with which the array will be referenced and size defines how
many elements the array will hold. The size must be an integer value or integer constant without
any sign
For e.g.

int marks[10];

The above statement declared array marks with 10 elements, marks[0] to marks[9].

 Initialization of array :

data_type array-name[size]={element-1,element-2,……..,element-n};
or
data_type array-name[ ]={element-1,element-2,……..,element-n};

For example,

int marks[5]={50,25,72,45,30};

Marks[0]=50;
Marks[1]=25;
Marks[2]=72;
Marks[3]=45;
Marks[4]=30;

Or int marks[ ]={50,25,72,45,30};

Also float price[ ] = {300.50, 250.50, 500.50, 175.50,


900.50};
and char grade[ ] = {„D‟ , „A‟ , „C‟„B‟, , „A‟ , „C‟ };

 Accessing an element at a particular index for one dimensional arrays

1. Individual element of an array can be accessed using the following syntax :


array_name[index or subscript];

For example, to assign a value to second location of array, we give the following statement
marks[1]=90;

2. For reading the value of fourth element in array_name marks, we give the following
statement :
scanf(“%d”,&marks[3]);

3. For writing the value of second element in array_name marks, we give the following
statement :
printf(“%d\t”,marks[1]);

Arrays can always be read or written through loop. If we read a one-dimensional array, it requires
one loop for reading and other for writing (printing) the array. For example :

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 10
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

(a) For reading the array


For reading the marks of 10 students :

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


{
scanf(“%d”, & marks [ i ] );
}

(b) For writing the array

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


{
printf(“%d\t”, marks [ i ] );
}
 Implementation of one-dimensional array in memory :

The address of a particular element in one-dimensional array is given by the relation :


Address of element a[k] = B+ W * k
where B is the base address of the array, W is the size of each element in array, and k is the
number of required element in the array (index of element) which should be a integer quantity.
For example :
Let the base address of first element of the array is 2000 (i.e. base address B is = 2000), and each
element of the array occupies four bytes in the memory, then address of fifth element of a one-
dimensional array a[4] will be given as :

Address of element a[4] = 2000 + 4 * 4


= 2000 + 16
=2016
Q.22 Write down the program for single dimension array.
1. Program 1 : WAP for array initialization
2. Program 2 : WAP for array input from user
3. Program 3 :WAP to display the sum and average of elements of an array
4. Program 4 : WAP to display the largest and smallest element of an array
5. Program 5 : WAP to insert a number in an array
6. Program 6 : WAP to delete a number from an array

Ans. Program 1 : WAP for array initialization

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
//Array declaration and initialization
int marks[ ]={50,60,70,80,90},i;
//Array output
printf("\nMarks of 5 students are : \n");
for(i=0;i<5;i++)
printf("%d\t",marks[i]);

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 11
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

getch( );
}

OUTPUT :

Marks of 5 students are :


50 60 70 80 90

Program 2 : WAP for array input from user

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
//Array declaration
int marks[5],i;
//Array input
printf("Enter marks of 5 students : \n");
for(i=0;i<5;i++)
scanf("%d",&marks[i]);
// Array output
printf("\nMarks of 5 students are : \n");
for(i=0;i<5;i++)
printf("%d\t",marks[i]);
getch( );
}
OUTPUT :

Enter marks of 5 students :


50 60 70 80 90
Marks of 5 students are :
50 60 70 80 90

Program 3 : WAP to display the sum and average of elements of an array

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
int A[5],i;
float sum=0,avg;
printf("Enter 5 elements of an array : \n");
for(i=0;i<5;i++)
scanf("%d",&A[i]);
for(i=0;i<5;i++)
sum=sum+A[i];
avg=sum/5;
printf("\nSum : %.2f",sum);
printf("\nAverage : %.2f",avg);

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 12
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

getch( );
}

OUTPUT :

Enter 5 elements of an array :

2 4 6 8 10

Sum : 30.00

Average : 6.00

Program 4 : WAP to display the largest and smallest element of an array

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
int A[5],i,max,min;
printf("Enter 5 elements of an array : \n");
for(i=0;i<5;i++)
scanf("%d",&A[i]);
max=min=A[0];
for(i=0;i<5;i++)
{
if(max<A[i])
max=A[i];
if(min>A[i])
min=A[i];
}
printf("\nLargest element in array : %d",max);
printf("\nSmallest element in array : %d",min);
getch( );

OUTPUT :

Enter 5 elements of an array :


3 9 5 1 8
Largest element in array : 9
Smallest element in array : 1

Program 5 : WAP to insert a number in an array

#include<stdio.h>
#include<conio.h>
void main( )
{

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 13
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

clrscr( );
int len;
printf("Enter size of array (max. 10) : ");
scanf("%d",&len);
int A[10],num,i,pos;
printf("\nEnter %d elements of array : \n",len);
for(i=0;i<len;i++)
scanf("%d",&A[i]);
printf("\nOriginal array is : \n");
for(i=0;i<len;i++)
printf("%d\t",A[i]);
printf("\n\nEnter the element to be inserted : ");
scanf("%d",&num);
printf("Enter the position of insertion : ");
scanf("%d",&pos);
pos--;
for(i=len-1;i>=pos;i--) // Shifts down one position
A[i+1]=A[i];
A[pos]=num;
if(pos>len)
printf("\nInsertion outside the array");
else
{
printf("\nNew array after insertion : \n");
len++;
for(i=0;i<len;i++)
printf("%d\t",A[i]);
}
getch( );
}

OUTPUT :

Enter size of array (max. 10) : 5


Enter 5 elements of array :
2 4 8 10 12
Original array is :
2 4 8 10 12
Enter the element to be inserted : 6
Enter the position of insertion : 3
New array after insertion :
2 4 6 8 10 12

Program 6 : WAP to delete a number from an array

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
int A[10],i,len,num,f=0;

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 14
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

printf("Enter the size of array (max. 10) : ");


scanf("%d",&len);
printf("\nEnter %d elements of an array : \n",len);
for(i=0;i<len;i++)
scanf("%d",&A[i]);
printf("\nOriginal array is : \n");
for(i=0;i<len;i++)
printf("%d\t",A[i]);
printf("\n\nEnter the element to delete : ");
scanf("%d",&num);
for(i=0;i<len;i++)
{
if(num==A[i])
{
f=1;
for(;i<len-1;i++)
A[i]=A[i+1];
len--;
break;
}
}
if(f==0)
printf("\nNumber not found in array");
else
{
printf("\nNew Array after deletion : \n");
for(i=0;i<len;i++)
printf("%d\t",A[i]);
}
getch( );
}

OUTPUT :
Enter the size of array (max. 10) : 5
Enter 5 elements of an array :
2 4 6 8 10
Original array is :
2 4 6 8 10
Enter the element to delete : 6
New Array after deletion :
2 4 8 10

Q.23 Describe Double dimension array in detail.

Ans. A double dimensional array is an array in which each element is itself an array. For
example, an array A[R][C] is an R by C table with R rows and C columns containing R * C
elements.

The number of elements in a two-dimensional array can be determined by multiplying number of


rows with number of columns. For example, the number of element in an array A[4][3] is
calculated as 4 * 3 = 12.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 15
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Implementation of Two-dimensional array in Memory

While storing the elements of a 2-D array in memory, these are allocated contiguous memory
locations. A two-dimensional array can be implemented in a programming language in two ways :

1. Row-major implementation
2. Column-major implementation

1. Row-major implementation :

Row-major implementation is a linearization technique in which elements of array are readed


from the keyboard row-wise i.e. the complete first row is stored, then the complete second row is
stored and so on. For example, an array A [3] [3] is stored in the memory as shown in Fig.(1)
below :

A A A A A A A A A
00 01 02 10 11 12 20 21 22

Row–1 Row–2 Row–3

The storage can be clearly understood by arranging array as matrix as shown below :

a00 a01 a02 Row1


a = a10 a11 a12 Row2
a20 a21 a22 Row3

Column-major implementation :

Column-major implementation is a linearization technique in which elements of array are


reader from the keyboard column-wise i.e. the complete first column is stored, then the complete

second column is stored and so on. For example, an array a[3][3] is stored in the memory as
shown in Fig.(1) below :

a00 a10 a20 a01 a11 a21 a02 a12 a22

Column–1 Column–2 Column –3

The storage can be clearly understood by arranging array as matrix as shown below :

a00 a01 a02


a = a10 a11 a12
a20 a21 a22
Column 1 Column 2 Column 3

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 16
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Double Dimensional Array declartion :

datatype arrayvariablename[rowsize][col.size];

For e.g.

int A[4][3];

where int is datatype, A is array variable_name, 4 is row size and 3 is columnsize.

Double Dimensional Array initialization :

datatype arrayname[rowsize][col. size]={{1st row elements},{2nd row elements},………};

For e.g.

int A[4][3]={{1,2,3}, {4,5,6,}, {7,8,9}, {10,11,12}};

Array input from user :

Row major form

for(r=0;r<4;r++)
for(c=0;c<3;c++)
scanf("%d",&A[r][c]);

Column major form

for(c=0;c<3;c++)
for(r=0;r<4;r++)
scanf("%d",&A[r][c]);

Array output :

for(r=0;r<4;r++)
{
for(c=0;c<3;c++)
printf("%d\t",A[r][c]);
printf("\n");
}

Q.24 Write down the program for double dimension array.


Program 1 : Double Dimensional array (Matrix) Initialization & Output
Program 2 : Double Dimensional array(Matrix) input & Output
Program 3 : Addition of Two 3 * 3 Matrices
Program 4 : WAP to display the transpose of a 3 * 3 matrix
Program 5 : WAP to multiply two 3 * 3 matrices

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 17
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Ans.

Program 1 : Double Dimensional array (Matrix) Initialization & Output

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
// Double Dim. Array declaration and initialization int
A[4][3]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}}; int r,c;
// Double Dim. Array Output
printf("\nGiven 4 * 3 matrix is : \n");
for(r=0;r<4;r++)
{
for(c=0;c<3;c++)
printf("%d\t",A[r][c]);
printf("\n");
}
getch( );
}

OUTPUT :
Given 4 * 3 matrix is :

1 2 3
4 5 6
7 8 9
10 11 12

Program 2 : Double Dimensional array(Matrix) input & Output

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
// Matrix declaration
int A[4][3],r,c;
// Matrix input
printf("\nEnter elements of a 4 * 3 matrix : \n");
for(r=0;r<4;r++)
for(c=0;c<3;c++)
scanf("%d",&A[r][c]);
// Matrix output
printf("\nGiven 4 * 3 matrix is : \n");
for(r=0;r<4;r++)
{
for(c=0;c<3;c++)

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 18
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

printf("%d\t",A[r][c]);
printf("\n");
}
getch( );
}

OUTPUT :
Enter elements of a 4 * 3 matrix :

1 2 3
4 5 6
7 8 9
10 11 12

Given 4 * 3 matrix is :

1 2 3
4 5 6
7 8 9
10 11 12

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 19
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Program 3 : Addition of Two 3 * 3 Matrices

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
// Matrix declaration
int A[3][3],B[3][3],C[3][3],r,c;
// Matrix input
printf("\nEnter elements of first 3 * 3 matrix : \n");
for(r=0;r<3;r++)
for(c=0;c<3;c++)
scanf("%d",&A[r][c]);
printf("\nEnter elements of second 3 * 3 matrix : \n");
for(r=0;r<3;r++)
for(c=0;c<3;c++)
scanf("%d",&B[r][c]);
// Matrix addition
printf("\nAddition of first two matrices : \n");
for(r=0;r<3;r++)
{
for(c=0;c<3;c++)
{
C[r][c]=A[r][c]+B[r][c];
printf("%d\t",C[r][c]);
}
printf("\n");
}
getch( );
}
OUTPUT :

Enter elements of first 3 * 3 matrix :

1 2 3
4 5 6
7 8 9

Enter elements of second 3 * 3 matrix :

2 3 4
5 6 7
8 9 10

Addition of first two matrices :

3 5 7
9 11 13
15 17 19

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 20
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Program 4 : WAP to display the transpose of a 3 * 3 matrix

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
int A[3][3],r,c;
printf("\nEnter elements of a 3 * 3 matrix :\n");
for(r=0;r<3;r++)
for(c=0;c<3;c++)
scanf("%d",&A[r][c]);
printf("\nOriginal matrix is :\n");
for(r=0;r<3;r++)
{
for(c=0;c<3;c++)
printf("%d\t",A[r][c]);
printf("\n");
}
printf("\nTranspose of given matrix is :\n");
for(r=0;r<3;r++)
{
for(c=0;c<3;c++)
printf("%d\t",A[c][r]);
printf("\n");
}
getch( );
}

OUTPUT :

Enter elements of a 3 * 3 matrix :

1 2 3
4 5 6
7 8 9
Original matrix is :

1 2 3
4 5 6
7 8 9

Transpose of given matrix is :

1 4 7
2 5 8
3 6 9

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 21
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Program 5 : WAP to multiply two 3 * 3 matrices

#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
int A[3][3],B[3][3],C[3][3],r,c,k;
printf("Enter elements of first 3 * 3 matrix : \n");
for(r=0;r<3;r++)
for(c=0;c<3;c++)
scanf("%d",&A[r][c]);
printf("\nEnter elements of second 3 * 3 matrix : \n");
for(r=0;r<3;r++)
for(c=0;c<3;c++)
scanf("%d",&B[r][c]);
printf("\nProduct of first two 3 * 3 matrices :\n");
for(r=0;r<3;r++)
{
for(c=0;c<3;c++)
{
C[r][c]=0;
for(k=0;k<3;k++)
C[r][c]=C[r][c]+(A[r][k]*B[k][c]);
printf("%d\t",C[r][c]);
}
printf("\n");
}
getch( );
}
OUTPUT :

Enter elements of first 3 * 3 matrix :

1 2 3
4 5 6
7 8 9

Enter elements of second 3 * 3 matrix :

1 2 3
4 5 6
7 8 9

Product of first two 3 * 3 matrices :

30 36 42
66 81 96
102 126 150

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 22
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.25 What is multi dimensional array ?

Ans. Multidimensional arrays :

The general syntax of a multidimensional array is :

datatype arrayname[size-1][size-2]………[size-n];

For example :

int A[5][2][3];

float B[2][5][3];

The simplest form of a multidimensional array is a two-dimensional array, which is also known
as array of an array.

Q.26 Explain sparse matrix.

Ans. If many of elements from a m x n matrix have a value 0 then the matrix is known as sparse matrix.
A matrix that is not sparse is known as a dense matrix. There is no precise definition of when a matrix
is sparse and when it is not, but it is a concept, which we can all recognize naturally. If the matrix is
sparse, we must consider an alternative way of representing it rather than a normal row major or column
major arrangement. This is because if majority of elements of the matrix are 0 then the alternative
through which we can store only the non-zero elements and keep intact the functionality of the matrix
can save a lot of memory space. Fig. (3) shows sparse matrix 5 * 6 with 5 non zero elements.

0 0 0 6 0 0
0 0 3 0 0 0
0 8 0 0 2 0
0 0 0 0 0 0
0 0 0 0 9 0

Q.27 Define memory allocation in detail.

Ans. There are two types of memory allocations possible in C:

(a) Static memory allocation (Compile-time allocation using arrays)

(b) Dynamic memory allocation (Run-time allocation using pointers)

Static memory allocation (using Arrays)

In Static memory allocation, the required amount of memory is allocated to the program elements at
the start of the program. Here the memory to be allocated to the variable is fixed and is determined by
the compiler at the compile time (if it is a single integer variable it allocates two bytes to it, if it is an

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 23
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

array of five integer values it allocates ten bytes to it and if it is a single float type of variable compiler
allocates four bytes to it. For example, consider the following declaration:
int x, y;
float A [5];

Dynamic memory allocation (using pointers)

The concept of Dynamic or Run-time memory allocation helps us to overcome this problem in arrays,
as well as allows us to be able to get the required portion of memory at run-time (or we say as the need
arises). This is best suited type of allocation where we do not know the memory requirement in advance,
which is the case with most of real-life problems. In other words, dynamic memory allocation gives
flexibility for programmer. As well as it makes efficient use of memory by allocating the required
amount of memory whenever needed, unlike static allocation where we declare the amount of memory
to be allocated statically.
MALLOC ( ) FUNCTION
malloc (number of elements * size of each element);

For example,

int *ptr;

ptr= malloc (10 * size of each element);


FREE ( ) FUNCTION
The free ( ) function is used to de-allocate the previously allocated memory using malloc ()

functions. The syntax of this function is:

free (ptr_var);

Q.28 What is the need of dynamic data structure?

Ans.The simplest one of data structures i.e. an array can be used only when their numbers of elements
along with elements sizes are predetermined, since the memory is reserved before processing. For this
reason, arrays are called static data structures. Now, consider a situation where exact numbers of
elements are not known. In such a case, estimates might go wrong. Also during processing, i.e., either
more memory is required or extra free spaces lie in the array. Another problem associated with arrays is
complexity involved in insertions and deletions of elements.

 Linked lists(Dynamic data structures) overcome the drawbacks of arrays as in linked lists number
of elements need not be predetermined, more memory can be allocated or released during the
processing as and when required, making insertions and deletions much easier and simpler.

 Dynamic memory allocation technique facilitates allocation of memory during the program
execution itself using malloc( ) function as and when required. Dynamic memory allocation also
facilitates release of memory using free( ) function, if memory is not required any more. Data
structures like linked lists and trees use this technique for their memory allocation

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 24
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.29 Explain link list in detail.

Ans. “A linked list is a linear collection of data elements, called node pointing to the next nodes by
means of pointers.”

 Each node is divided into two parts: the first part containing the information of the element, and
the second part called the link or next pointer containing the address of the next node in the list.
Start

1000

Info Link Info Link Info Link

10 2000 20 3000 30 0

1000 2000 3000


Node-1 Node-2 Node-3

OPERATIONS ON LINKED LISTS

The basic operations to be performed on the linked lists are as follows :


1. Creation 2. Insertion 3. Deletion 4. Traversing
5. Searching 6. Concatenation 7. Display

Creation: This operation is used to create a linked list.

Insertion: This operation is used to insert a new node in the linked list at the specified position. A new
node may be inserted :

 At the beginning of a linked list


 At the end of a linked list
 At the specified position in a linked list.
 If the list itself is empty, then the new node is inserted as a first node.

Deletion:This operation is used to delete a node from the linked list. A node may be deleted from
 Beginning of the link list
 End of the link list
 At the specific position of the link list

Traversing:It is a process of going through all the nodes of a linked list from one end to the other end.
 It we start traversing from the very first node towards the last node, it is called forward
traversing.

 It we start traversing from the very last node towards the first node, it is called reverse traversing

Searching:If the desired element is found, we signal operation “SUCCESSFULL”. Otherwise, we signal
it as “UNSUCCESSFULL”.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 25
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Concatenation:It is a process of appending (joining) the second list to the end of the first list consisting
of m nodes. When we concatenate two lists, the second list has n nodes, then the concatenated list will
be having (m + n) nodes. The last node of the first linked list is modified so that it is now pointing to the
first node in the second list.

Display:This operation is used to print each and every node‟s information. We access each node from
the beginning (or the specified position) of the list and output the data stored there.

Q.30 Explain the different type of link list ?

Ans.
TYPES OF LINKED LISTS

Basically, we can put linked lists into the following four types:

Singly linked list (Linear linked list)


Doubly linked list
Circular linked list
Circular doubly linked list

Singly linked list

A singly linked list is one in which all nodes are linked together in some sequential manner. Hence, it is
also called linear linked list. Clearly, it has the beginning and the end. The problem with this list is that
we cannot access the predecessor node (previous node) from the current node. This can be overcome by
doubly linked lists. A linear linked list is shown in Fig. (1).

Doubly linked list

A Doubly linked list is one in which all nodes are linked together by multiple links which help in
accessing both the successor node (next node) and predecessor node (previous node) for any random
node within the list. Therefore, each node in a doubly linked list points to the left node (previous) and
the right node (next). This helps to traverse the list in the forward direction and backward direction. A
doubly linked list is shown in Fig. (2).

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 26
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Circular linked list :A circular linked list is one which has no beginning and no end. A singly linked
list can be made circular linked list by simply storing the address of the very first node in the link field of
the last node. A circular linked list is shown in Fig. (3).

Circular doubly linked list: A circular doubly linked list is one which has both the successor pointer
and predecessor pointer in circular manner. A Circular doubly linked list is shown in Fig. (4).

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 27
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.31 Write down the algorithm for the following:


i) Algorithm to insert node at the beginning of the singly linked list
ii) Algorithm to insert node at the end of the singly linked list
iii) Algorithm to insert node at a specific location in the singly linked list
iv) Algorithm to delete node from the beginning of the singly linked list
v) Algorithm to delete node from the end of the singly linked list
vi) Algorithm to delete node from a specific location in the singly linked list

Ans.

INSERTION
Let PTR is the structure pointer which allocates memory for the new node at the beginning of the
singly linked list & NUM is the element to be inserted into the linked list, INFO represents the
information part of the new node and LINK represents the link or next pointer of the new node
pointing to the address of next node. START represents the address of first node. Initially, before
inserting first node in the singly linked list, START=NULL

(I) Algorithm to insert node at the beginning of the singly linked list

Step 1 : Allocate memory for the new node using PTR.


Step 2 : Read NUM to be inserted into singly linked list.
Step 3 : Set PTR->INFO = NUM
Step 4 : Set PTR->LINK=START;
Step 5 : Set START:=PTR
Step 6 : Exit

(II) Algorithm to insert node at the end of the singly linked list

Step 1 : Allocate memory for the new node using PTR.


Step 2 : Read NUM to be inserted into singly linked list.
Step 3 : Set PTR->INFO = NUM
Step 4 : Set PTR->LINK := NULL
Step 5 : If START = NULL : then
Set START := PTR.
Else
Set TEMP := START;
Repeat while TEMP->LINK !=NULL
Set TEMP := TEMP->LINK.
[End of loop]
Set TEMP-> LINK := PTR.
[End of If Else Structure]
Step 6 : Exit

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 28
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

(II) Algorithm to insert node at a specific location in the singly linked list

Step 1 : Read the location LOC where you want to insert the node.
Step 2 : If LOC > 1 : then
Set TEMP := START.
Repeat loop for I = 1 to LOC – 1
TEMP := TEMP->LINK.
If TEMP := NULL : then
Set F :=1 and Exit from loop.
[End of If Statement]
[End of loop]
If (F=1 OR (START=NULL AND LOC>1)) : then
Write : “Total nodes in list are lesser than this position.”
Write : “So Node cannot be inserted.” and return.
[End of If structure]
[End of Step 2 If Structure]
Step 3 : Allocate memory for the new node using PTR.
Step 4 : Read NUM to be inserted into singly linked list.
Step 5 : Set PTR->INFO = NUM
Step 6 : If LOC :=1 : then
Set PTR->LINK := START.
Set START := PTR.
Else
Set PTR->LINK := TEMP->LINK.
TEMP->LINK := PTR.
[End of If Else Structure].
Step 7 : Exit

(B) DELETION

Let PTR is the structure pointer which deallocates memory of the node at the beginning of the
singly linked list & NUM is the element to be deleted from the linked list, INFO represents the
information part of the deleted node and LINK represents the link or next pointer of the deleted
node pointing to the address of next node. START represents the address of first node

(IV) Algorithm to delete node from the beginning of the singly linked list

Step 1 : If START := NULL : then


Write : “List is empty” and return.
Step 2 : Set PTR := START.
Step 3 : Set NUM := PTR->INFO.
Step 4 : Write : “Deleted element from the beginning of the singly linked list : “,NUM.
Step 5 : Set START := START->LINK.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 29
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Step 6 : Deallocate memory of the node at the beginning of singly linked list using PTR.
Step7 : Exit

(V) Algorithm to delete node from the end of the singly linked list

Step 1 : If START := NULL : then


Write : “List is empty” and return.
Step 2 : If START->LINK := NULL : then
Set PTR := START.
Set START := NULL.
Else
Set TEMP := START.
Set PTR := PTR->LINK.
Repeat loop while PTR->LINK!=NULL
Set TEMP := PTR.
Set PTR := PTR->LINK.
[End of loop]
Set TEMP->LINK := NULL.
[End of Step 2 If Else Structure]
Step 3 : Set NUM := PTR->INFO.
Step 4 : Write : “Deleted element from the end of the singly linked list : “,NUM.
Step 5 : Deallocate memory of the node at the end of singly linked list.
Step 6 : Exit

(vi) Algorithm to delete node from a specific location in the singly linked list

Step 1 : If START := NULL : then


Write : “List is empty” and return.
Step 2 : Set PTR := START.
Step 3 : Read the location LOC from where you want to delete the node.
Step 4 : If LOC := 1 : then
START := PTR->LINK
Else
Repeat loop for I = 1 to LOC.
Set TEMP := PTR.
Set PTR := PTR->LINK.
If PTR = NULL : then
Write : “Total nodes in the list are lesser than this position”.
Write : “So node cannot be deleted” and return.
[End of If structure]
[End of loop]
Set TEMP->LINK := PTR->LINK.
[End of Step 4 If Else structure]
Step 5 : Set NUM := PTR->INFO.
Step 6 : Write : “Deleted element from the singly linked list : “,NUM.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 30
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Step 7 : Deallocate memory of the node at the location LOC of singly linked list.
Step 8 : Exit

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 31
KRISHNA INSTITUTE OF TECHNOLOGY

UNIT-2
 Stacks: Abstract Data Type
 Primitive Stack operations: Push & Pop
 Array and Linked Implementation of Stack in C
 Application of stack: Prefix and Postfix Expressions
 Evaluation of postfix expression
 Recursion
 Tower of Hanoi Problem
 Tail recursion
 Queues
 Operations on Queue: Create, Add, Delete, Full and Empty
 Circular queues
 Array and linked implementation of queues in C
 Dequeue and Priority Queue.

Page 32
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

Q.1 Define stack?

Ans. A stack is a non-primitive linear data structure. It is an ordered list in which addition of
new data item and deletion of already existing data item is done from only one end, known as
Top of Stack (TOS). As all the deletion and insertion in a stack is done from top of the stack, the
last added element will be the first to be removed from the stack. Due to this reason, the stack is
also called Last-In-First-Out (LIFO) type of list. Consider some examples,

1. A common model of a stack is plates in a marriage party. Fresh plates are “pushed” onto
the top and “popped” off the top.

2. Some of you may eat biscuits. If you assume only one side of the cover is torn and biscuits
are taken off one by one. This is called popping and similarly, if you want to preserve some
biscuits for some time later, you will put them back into the pack through the same torn
end called pushing.

Q2. Give the basic operation of stack.

Ans. The basic operations that can be performed on stack are as follows :

 PUSH : The process of adding a new element to the top of the stack is called PUSH
operation. Pushing an element in the stack involve adding of element, as the new element
will be inserted at the top, so after every push operation, the top is incremented by one. In
case the array is full and no new element can be accommodated, it is called STACK-
FULL condition. This condition is called STACK OVERFLOW.

 POP : The process of deleting an element from the top of the stack is called POP
operation. After every pop operation, the stack is decremented by one. If there is no
element on the stack and the pop is performed then this will result into STACK
UNDERFLOW condition.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 33
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

Q.3 Write down the algorithm for inserting an item into the stack (PUSH).

Ans. Let STACK[MAXSIZE] is an array for implementing the stack, MAXSIZE represents the
max. size of array STACK. NUM is the element to be pushed in stack & TOP is the index
number of the element at the top of stack.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 34
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

Step 1 : [Check for stack overflow ? ]


If TOP = MAXSIZE – 1, then :
Write : „Stack Overflow‟ and return.
[End of If Structure]

Step 2 : Read NUM to be pushed in stack.

Step 3 : Set TOP = TOP + 1 [Increases TOP by 1]


Step 4 : Set STACK[TOP] = NUM [Inserts new number NUM in new TOP Position]
Step 5 : Exit

Q.4 Write down the C function for push operation in stack.

Ans. C function for push operation in stack :

void push()
{
if(top==MAXSIZE-1)
{
printf("\n\nStack is full(Stack overflow)");
return;
}
int num;
printf("\n\nEnter the element to be pushed in stack : ");
scanf("%d",&num);
top++;
stack[top]=num;
}

Q.5 Write down the algorithm for deleting an item from the stack (POP)

Ans. Let STACK[MAXSIZE] is an array for implementing the stack where MAXSIZE
represents the max. size of array STACK. NUM is the element to be popped from stack & TOP
is the index number of the element at the top of stack.

Step 1 : [Check for stack underflow ? ]


If TOP = -1 : then
Write : „Stack underflow‟ and return.

[End of If Structure]
Step 2 : Set NUM = STACK[TOP] [Assign Top element to NUM]
Step 3 : Write „Element popped from stack is : „,NUM.
Step 4 : Set TOP = TOP - 1 [Decreases TOP by 1]
Step 5 : Exit

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 35
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

Q.6 Write the function of the Stack POP operation in C.

Ans. The function of the Stack POP operation in C is as follows :

void pop()
{
if(top== -1)
{
printf("\n\nStack is empty(Stack underflow)");
return;
}
int num;
num=stack[top];
printf("\n\nElement popped from stack : %d",num);
top--;
}

Q.7 Write down the algorithms for push & pop for dynamic implementation using pointers.
1.Algorithm for inserting an item into the stack (PUSH)
2.Algorithm for deleting an item from the stack (POP)

Ans. Algorithm for inserting an item into the stack (PUSH)


Let PTR is the structure pointer which allocates memory for the new node & NUM is the
element to be pushed into stack, TOP represents the address of node at the top of the stack,
INFO represents the information part of the node and LINK represents the link or next
pointer pointing to the address of next node.
Step 1 : Allocate memory for the new node using PTR.
Step 2 : Read NUM to be pushed into stack.
Step 3 : Set PTR->INFO = NUM
Step 4 : Set PTR->LINK=TOP
Step 5 : Set TOP = PTR
Step 6 : Exit

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 36
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

(B) Algorithm for deleting an item from the stack (POP)


Let PTR is the structure pointer which deallocates memory of the node at the top of stack &
NUM is the element to be popped from stack, TOP represents the address of node at the top of
the stack, INFO represents the information part of the node and LINK represents the link or next
pointer pointing to the address of next node.
Step 1 : [Check for Stack Underflow ?]
If TOP = NULL : then
Write „Stack Underflow‟ &
Return.
[End of If Structure]
Step 2 : Set PTR=TOP.
Step 3 : Set NUM=PTR->INFO
Step 4 : Write „Element popped from stack is : „,NUM
Step 5 : Set TOP=TOP->NEXT
Step 6 : Deallocate memory of the node at the top using PTR.
Step 5 : Exit
Q. 8 Write down the function for push and pop operation in C for dynamic representation
of stack.
Ans. Function for PUSH Operation using pointers:
void push()
{
struct stack *ptr;
int num;
ptr=(struct stack *)malloc(sizeof(struct stack));
printf("\nEnter the element to be pushed in stack : ");
scanf("%d",&num);
ptr->info=num;

ptr->link=top;
top=ptr;
}

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 37
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

Function for POP Operation using pointers

void pop()
{
if(top==NULL)
{
printf("\nStack is empty(Stack underflow).");
return;
}
struct stack *ptr;
int num;
ptr=top;
num=ptr->info;
printf("\nElement popped from stack : %d",num);
top=top->link
free(ptr);
}

Q.9 What is polish notion ?

Ans. A polish mathematician suggested a notation called Polish notation, which gives two
alternatives to represent an arithmetic expression.

 The notations are prefix and postfix notations.


 The fundamental property of Polish notation is that the order in which the operations are
to be performed is completely determined by the positions of the operators and operands
in the expression.
 Hence parenthesis are not required while writing expressions in Polish notation. The Two
types of polish notations are given below :
1. Prefix notation
2. Postfix notation

Q.10 Define Prefix notation?

Ans. The prefix notation is a notation in which the operator is written before the operands. For
example, + AB
As the operator „+‟ is written before the operands A and B, this notation is called prefix notation
(pre means before).
Q.11 Define Postfix notation?

Ans. The postfix notation is a notation in which the operator is written after the operands. For
example,
AB +

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 38
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

As the operator „+‟ is written after the operands A and B, this notation is called postfix notation
(post means after).

Q.12 Define Infix notation?

Ans. The infix notation is what we come across in our general mathematics, where the operator
is written in-between the operands. For example : The expression to add two numbers A and B is
written in infix notation as :
A+B
Note that the operator „+‟ is written in-between het operands A and B. The reason why this
notation is called infix, is the place of operator in the expression.

Q.13 Write down the algorithm for converting infix expression into postfix expression.
Ans. Algorithm for converting infix expression into postfix expression

Let Q is an arithmetic expression written in infix notation. This algorithm finds the equivalent
postfix expression P.

1. Push “(“ onto STACK, and add”)” to the end of Q.


2. Scan Q from left to right and repeat Steps 3 to 6 for each element of Q until the stack is
empty.
3. If an operand is encountered, add it to P.
4. If a left parenthesis is encountered, push it onto STACK.
5. If an operator Ä is encountered, then :
(a) Add Ä to STACK. [End of If structure].

(b) Repeatedly pop from STACK and add P each operator (on the top of STACK) which
has the same precedence as or higher precedence than Ä.
6. If a right parenthesis is encountered, then :
(a) Repeatedly pop from STACK and add to P each operator (on the top of STACK until a
left parenthesis is encountered.
(b) Remove the left parenthesis. [Do not add the left parenthesis to P.]
[End of if structure.]
[End of Step 2 loop].
7. Exit.

Q. 14 Write down the steps for the evaluation of postfix expression.

Ans.To evaluate a postfix expression using Stack data structure we can use the following steps...

1. Read all the symbols one by one from left to right in the given Postfix Expression

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 39
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

2. If the reading symbol is operand, then push it on to the Stack.


3. If the reading symbol is operator (+ , - , * , / etc.,), then perform TWO pop operations and
store the two popped oparands in two different variables (operand1 and operand2). Then
perform reading symbol operation using operand1 and operand2 and push result back on
to the Stack.
4. Perform a pop operation and display the popped value as final result.

Q.15 Solve the postfix notion : 2 3 4 + * 6 –


Ans

Input Stack contents


token Operation (top on the right) Details

Push on the
2 stack 2

Push on the
3 stack 2, 3

Push on the
4 stack 2, 3, 4

Pop two values: 3 and 4 and


push the result 7 on the
+ Add 2, 7 stack

Pop two values: 2 and 7 and


push the result 14 on the
* Multiply 14 stack

Push on the
6 stack 14, 6
Pop two values: 14 and 6
and push the result 8 on the
– Subtract 8 stack

(End of (Return the Pop the only value 8 and


tokens) result) 8 return it

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 40
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

Q.16 Explain the term recursion?

Ans. The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain
problems can be solved quite easily.

Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree


Traversals, DFS of Graph, etc.

Q.17 Explain Tower of Hanoi problem?

Ans. Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more
than one rings is as depicted −
These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one
sits over the larger one. There are other variations of the puzzle where the number of disks
increase, but the tower count remains the same.
A few rules to be followed for Tower of Hanoi are −

 Only one disk can be moved among the towers at any given time.
 Only the "top" disk can be removed.
 No large disk can sit over a small disk.
Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps.
The steps to follow are −
Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest

A recursive algorithm for Tower of Hanoi can be driven as follows −


START
Procedure Hanoi(disk, source, dest, aux)

IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF

END Procedure
STOP

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 41
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 42
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

Q.18 Give one example of recursion.

Ans. int factorial(int n)

{
if (n == 0)
return 1;
return n*factorial(n-1);
}
Q. 19 Define Queue?

Ans. Queue is a non-primitive linear data structure that permits insertion of an element at one
end and deletion of an element at the other end.

 The end at which the deletion of an element take place is called front, and the end at
which insertion of a new element can take place is called rear.
 The deletion or insertion of elements can take place only at the front and rear end of the
list respectively.
 The first element that gets added into the queue is the first one to get removed from the
list. Hence, Queue is also referred to as First-In-First-Out (FIFO) list.

Q.21 Explain queue with the help of example.

Ans. Let us take the example of queue with 7 elements:

1 2 3 4 5 6 7
F=0 R=0
Queue is empty

Push A A
F=1 R=1

Push B A B
F=1 R=2

Push C A B C
F=1 R=3

Push D A B C D
F=1 R=4

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 43
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

Pop B C D
F=2 R=4

Pop C D
F=3 R=4

Push E C D E
F=3 R=5

Push F C D E F
F=3 R=6

Push G C D E F G
F=3 R=7

Push H C D E F G
F=3 R=7
Overflow

Q.22 State the implementation of the queue.

Ans. Queues can be implemented in two ways :

1. Static implementation (using arrays)


2. Dynamic implementation (using pointers)

Q.23 Explain the static representation of Queue?

Ans. Static implementation of Queue is represented by arrays. If Queue is implemented using


arrays, we must be sure about the exact number of elements we want to store in the queue,
because we have to declare the size of the array at design time or before the processing starts. In
this case, the beginning of the array will become the front for the queue and the last location of
the array will act as rear for the queue. Fig. (3) shows the representation of a queue as an array.

arr[0] arr[1] arr[2] arr[3] arr[4] arr[5] arr[6] arr[7]

10 20 30 40 50 60 70 80

Front Rear

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 44
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

The following relation gives the total number of elements present in the queue, when
implemented using arrays :

REAR – FRONT + 1
Also note that if front > rear, then there will be no element in the queue or queue is empty.

Q.24 What operations can be perform on queue?

Ans. OPERATIONS ON A QUEUE


The basic operations that can be performed on queue are :
1. To Insert an element in a Queue

2. To Delete an element from a Queue.


3. To Traverse all elements of a Queue.

Q.25 Write down the algorithm for Insertion in a linear queue.

Ans. Algorithm for Insertion in a Linear Queue

Let QUEUE[MAXSIZE] is an array for implementing the Linear Queue & NUM is the element
to be inserted in linear queue, FRONT represents the index number of the element at the
beginning of the queue and REAR represents the index number of the element at the end of the
Queue.

Step 1 :If REAR = (MAXSIZE –1) : then


Write : “Queue Overflow” and return
[End of If structure]
Step 2 : Read NUM to be inserted in Linear Queue.
Step 3 : Set REAR := REAR + 1
Step 4 : Set QUEUE[REAR] := NUM
Step 5 : If FRONT = –1 : then
Set FRONT=0.
[End of If structure]
Step 6 : Exit

Q.26 Write down the algorithm for deletion in a linear queue.

Ans. Algorithm for Deletion from a Linear Queue

Let QUEUE[MAXSIZE] is an array for implementing the Linear Queue & NUM is the element
to be deleted from linear queue, FRONT represents the index number of the element at the

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 45
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

beginning of the queue and REAR represents the index number of the element at the end of the
Queue.

Step 1 : If FRONT = -1 : then


Write : “Queue Underflow” and return
[End of If structure]
Step 2 : Set NUM := QUEUE[FRONT]
Step 3 : Write “Deleted item is : ”, NUM
Step 4 : Set FRONT := FRONT + 1.
Step 5 : If FRONT>REAR : then
Set FRONT := REAR := -1.
[End of If structure]
Step 6 : Exit

Q.27 Write down the C function for insertion and deletion in a linear queue using array.

Ans. Function for insertion in a linear queue (using arrays) :


void lqinsert()
{
int num;
if(rear==MAXSIZE-1)
{
printf("\nQueue is full (Queue overflow)");
return;
}
printf("\nEnter the element to be inserted : ");
scanf("%d",&num);
rear++;
queue[rear]=num;
if(front==-1)
front=0;
}
Function(Procedure) for Deletion from a Linear Queue :

void lqdelete()
{
if(front == -1)
{
printf("\nQueue is empty (Queue underflow)");
return;
}
int num;
num=queue[front];

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 46
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

printf("\nDeleted element is : %d",num);


front++;
if(front>rear)
front=rear=-1;
}

Q.28 Write down the algorithms for insertion & deletion in a linear queue for dynamic
implementation using linked list.
Ans. Algorithms for insertion & deletion in a linear queue for dynamic implementation
using linked list :

1) Algorithm for inserting an element in a Linear Queue :

Let PTR is the structure pointer which allocates memory for the new node & NUM is the
element to be inserted into linear queue, INFO represents the information part of the node
and LINK represents the link or next pointer pointing to the address of next node. FRONT
represents the address of first node, REAR represents the address of the last node. Initially,
Before inserting first element in the queue, FRONT=REAR=NULL.

Step 1 : Allocate memory for the new node using PTR.


Step 2 : Read NUM to be inserted into linear queue.
Step 3 : Set PTR->INFO = NUM
Step 4 : Set PTR->LINK= NULL
Step 5 : If FRONT = NULL : then
Set FRONT=REAR=PTR
Else
Set REAR->LINK=PTR;
Set REAR=PTR;
[End of If Else Structure]
Step 6 : Exit

2) Algorithm for Deleting a node from a Linear Queue :

Let PTR is the structure pointer which deallocates memory of the first node in the linear queue &
NUM is the element to be deleted from queue, INFO represents the information part of the
deleted node and LINK represents the link or next pointer of the deleted node pointing to the
address of next node. FRONT represents the address of first node, REAR represents the address
of the last node.
Step 1 : If FRONT = NULL : then

Write „Queue is Empty(Queue Underflow)‟ and return.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 47
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

[End of If structure]
Step 2 : Set PTR = FRONT
Step 3 : Set NUM = PTR->INFO
Step 4 : Write „Deleted element from linear queue si : „,NUM.
Step 5 : Set FRONT = FRONT->LINK
Step 6 : If FRONT = NULL : then
Set REAR = NULL.
[End of If Structure].
Step 7 : Deallocate memory of the node at the beginning of queue using PTR.
Step 8 : Exit
Q.29 Define priority Queue?

Ans. A priority queue is a collection of elements where the elements are stored according to
their priority levels. The order in which the elements get added or removed is decided by the
priority of the element.
Following rules are applied to maintain a priority queue :
(1) The element with a higher priority is processed before any element of lower priority.

(2) If there are elements with the same priority, then the element added first in the queue
would get processed.

Priority queues are used for implementing job scheduling by the operating system where jobs
with higher priorities are to be processed first. Another application of Priority queues is
simulation systems where priority corresponds to event times.

There are mainly two ways of maintaining a priority queue in memory. One uses a one-way list,
and the other uses multiple queues. The ease or difficultly in adding elements to or deleting them
from a priority queue clearly depends on the representation that one chooses

Q.30 Give two application of queue?

Ans. Applications of queue are:


1. Round Robin technique for processor scheduling is implemented using queues.

2. All types of customer service (like railway ticket reservation) center software‟s are
designed using queues to store customers information.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 48
KRISHNA INSTITUTE OF TECHNOLOGY

UNIT 3
 Trees: Basic terminology
 Binary Trees
 Binary Tree Representation: Array Representation and Dynamic
Representation,
 Complete Binary Tree
 Algebraic Expressions
 Extended Binary Trees
 Array and Linked Representation of Binary trees
 Tree Traversal algorithms: Inorder, Preorder and Postorder
 Threaded Binary trees
 Traversing Threaded Binary trees, Huffman algorithm.

Page 49
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.1 Define Tree?

Ans. A Tree is a non-linear data structure in which items are arranged in a sorted sequence. It is
used to represent hierarchical relationship existing amongst several data items.

The graph theoretic definition of tree is : it is a finite set of one or more data items (nodes) such that
(a) There is a special data item called the root of the tree.
(b) And its remaining data items are partitioned into number of mutually exclusive (i.e. disjoint)
subsets, each of which is itself a tree. And they are called subtrees.

A tree is shown in Fig.

Fig : A Tree

Q.2 Explain the following terms:

1. Root
2. Node
3. Degree of a node
4. Degree of a tree
5. Terminal node (s)
6. Non-terminal node (s)
7. Siblings
8. Level
9. Edge
10. Path
11. Depth
12. Forest
Ans.
1. Root: It is specially designed data item in a tree. It is the first in the hierarchical arrangement of
data items. In the above tree, A is the root item.

2. Node : Each data item in a tree is called a node. It is the basic structure in a tree. It specifies the
data information and links (branches) to other data items. There are 13 nodes in the above tree.

3. Degree of a node: It is the number of subtrees of a node in a given tree. In the above tree
The degree of node A is 3
The degree of node C is 1
The degree of node B is 2

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 50
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

The degree of node H is 0


The degree of node I is 3.

4. Degree of a tree: It is the maximum degree of nodes in a given tree. In the above tree, the node
A has degree 3 and another node I is also having its degree 3. In all this value is the maximum.
So, the degree of the above tree is 3.

5. Terminal node (s):A node with degree zero is called a terminal node or a leaf. In the above tree,
there are 7 terminal nodes. They are E, J, G, H, K , L and M.

6. Non-Terminal Node (s):Any node (except the root node) whose degree is not zero is called non-
terminal node. Non-terminal nodes are the intermediate nodes in traversing the given tree from
its root node to the terminal nodes (leaves). There are 5 non-terminal nodes.

7. Siblings: The children nodes of a given parent node are called siblings. They are also called
brothers. In the above tree,
E and F are siblings of parent node B.
K, L and M are siblings of parent node I.
8. Level: The entire tree structure is leveled in such a way that the root node is always at level 0.
Then, its immediate children are at level 1 and their immediate children are at level 2 and so on
upto the terminal nodes. In general, if a node is at level n, then the children will be at level n + 1
in the four levels.

9. Edge: It is a connecting line of two nodes. That it, the line drawn from one node to another node
is called an edge.

10. Path: It is a sequence of consecutive edges from the source node to the destination node. IN the
above tree, the path between A and J is given by the node pairs,
(A, B), (B, F) and (F, J)
11. Depth: It is the maximum level of any node in a given tree. In the above tree, the root node A
has the maximum level i.e., the number of levels one can descend the tree from its root to the
terminal nodes (leaves). The term height is also used to denote the depth.

12. Forest: It is a set of disjoint trees. In a given tree, if you remove its root node then it becomes a
forest. In the above tree, there is forest with three trees.

Q.3 Explain the term binary trees?

Ans. A binary tree consists of a finite set of elements that can be partitioned into three distinct sub-sets
called the root, the left sub-tree and the right sub-tree. If there are no elements in the binary tree it is
called an empty binary tree.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 51
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.4 Explain the terminology used in binary tree ?


Ans.
1. Node :Each element present in a binary tree is called a node of that tree.

2. Root :The element that represents the base node of the tree is called the root of the tree.

3. The left and right sub-tree : Apart from the root, the other two sub-sets of a binary tree are
binary trees. They are called the left and right sub-trees of the original tree. Any of these sub-
sets can be empty.

4. Leaf node : A node that does not have any sons (such as D, G, H or I shown in Fig.(2) is called
a leaf node.

5. Ancestor and descendant : A node A is said to be an ancestor of node B, if A is either the


father of B or the father of some ancestor of B. For example, in the tree shown in Fig. (2), A is
an ancestor of C. A node B is said to be a left descendant of node A if B is either the left son of
A or a descendant of the left son of A. In a similar fashion we can define the right descendant.

Q.5 Define the term strictly binary tree ?

Ans. A binary tree is called a strictly binary tree if every non-leaf node in a binary tree has non-empty
left and right sub-trees. For example, the tree shown in Fig. (3) is a strictly binary tree, whereas, the tree
shown in Fig. (2) is not a strictly binary tree since nodes B and E in it have one son each

Fig. (3) Strictly binary tree

1. Degree :The number of nodes connected to a particular node is called the degree of that node.
For example, in Fig. (3) the node containing data D has a degree 3. The degree of a leaf node is
always one.

2. Level :The root node of the tree has level 0. The level of any other child node is one more than
the level of its father. For example, in the binary tree shown in Fig. (2), node E is at level 2 and
node H is at level 3.

3. Depth :The maximum level of any leaf node in the tree is called the depth of the binary tree. For
example, the depth of the tree shown in Fig. (2) is 3.

Q.6 Explain the term Complete binary tree?

Ans.A strictly binary tree all of whose leaf nodes are at the same level is called a complete binary tree.
Fig. (5) shows the complete binary tree. The depth of this tree is 2.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 52
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Fig. (5) Complete binary tree

Q.7 Define Extended Binary Tree?

Ans. Extended Binary tree :A binary tree can be converted to an extended binary tree by adding new
nodes to its leaf nodes and to the nodes that have only one child. These new nodes are added in such a
way that all the nodes in the resultant tree have either 0 or 2 children. The extended tree is also known as
a 2-tree. The nodes of the original tree are called internal nodes and the new nodes that are added to
binary tree, to make it an extended binary tree are called external nodes.
Fig. 6 shows how extended binary tree (Fig 6(b) can be obtained by adding new nodes to original tree
(Fig. 6(a)). In Fig. 6, all the nodes with circular shape are internal nodes and all the nodes with square
shape are external nodes.

A few important points about Extended Binary tree are :


(1) If a tree has n nodes then the number of branches it has is (n-1).
(2) Except the root node every node in a tree has exactly one parent.
(3) Any two nodes of a tree are connected by only one single path.
(4) For a binary tree of height h the maximum number of nodes can be 2h+1 – 1 .
(5) Any binary tree with n internal nodes has (n + 1) external nodes.

Fig. (6) Converting a binary tree T into a 2-tree

Q.8 Explain the array representation of tree.

Ans. Array representation of a Binary Tree :An array can be used to store the nodes of a binary tree.
The nodes stored in an array are accessible sequentially. The maximum number of nodes is specified by
MAXSIZE. In C, arrays start with index 0 to (MAXSIZE – 1). Here, numbering of binary tree nodes
start from 0.

The root node is always at index 0. Then, in successive memory locations the left child and right child
are stored. Consider a binary tree with only three nodes as shown. Let BT denote the binary tree.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 53
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Fig 7

Here, A is the father of B and C, B is the left child of A and C is the right child of A. Let us extend the
above tree by one more level as shown below :

1. Father (n) : The father of node having index n is at floor ((n - 1) / 2), if n is not equal to 0. If n =
0, then it is the root node and has no father.
Example : Consider a node numbered 3 (i.e. D). The father of D, no doubt, is B whose index is 1.
This is obtained from floor ((3 – 1) / 2 = floor (2/2) = 1

2. Lchild (n) : The left child of node numbered n is at (2n + 1). For example, in the above binary
tree
Eg1: Lchild (A) = Lchild(0)
=2 *0 + 1
=1
i.e., the node with index 1 which is nothing but B.

Eg2: Lchild (C) = Lchild(2) =2 *2 + 1=5

i.e., the node with index 5 which is nothing but F.

Rchild (n) : The right child of node numbered n is index (2n + 2). For example, in the above
binary tree,

Rchild(A) = Rchild(0)
=2 *0 + 1= 2

i.e., the node with index 2 which is nothing but C.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 54
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Rchild(B) = Rchild(1)= 2 * 1 + 2= 4

i.e. the node with index 4 which is nothing but E.

3. Siblings : If the left child at index n is given then its right sibling (or brother) is at (n + 1).
And, Similarly, if the right child at index n is given, then its left sibling is at (n - 1). For
example, the right sibling is at (n – 1) of node indexed 4 is at index 5 in an array representation.

Q.9 Explain the link representation of tree ?

Ans. Link representation of a Binary tree : Binary tree can be represented either using array
representation or using a linked list representation. The basic component to be represented in a binary
tree is a node. The node consists of three fields such as
1. Data
2. Left child
3. Right child

The data field holds the value to be given. The left child is a link field which contains the address of its
left node and the right child contains the address of the right node. Fig. shows a structure of a node.

Fig. A node structure of a binary tree

The logical representation of the node in C is given below :


struct tree
{
char info;
struct node *left;
struct node *right;
};
struct tree *ptr;

Consider the following binary tree :

Fig. (12) A Binary tree

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 55
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

And, its linked representation is shown in Fig. (13). In the above binary tree all the data items are of type
char.

Fig. (13) : Linked representation of a Binary Tree

 A binary tree contains one root node and some non-terminal and terminal nodes (leaves).
 It is clear from the observation of a binary tree that the non-terminal nodes have their left child
and right child nodes. But, the terminal nodes have no left child and right child nodes.
 Their lchild and rchild pointer are set to NULL.
 Here, the non-terminal nodes are called internal nodes and terminal nodes are called external
nodes.
 In a specific application user may maintain two sets of nodes for both internal nodes and external
nodes.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 56
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.10 State all the operation performed in binary tree?

Ans.OPERATIONS ON BINARY TREES

The basic operations to be performed on a binary tree are listed in Table (1).

S.No. Operation Description


1. Create It create an empty binary tree.

2. MakeBT It creates a new binary tree having a single node with data field set to
some value.

3. EmptyBT It returns true if the binary tree is empty. Otherwise if returns false.

4. Lchild It returns a pointer to the left child of the node. If the node has no left
child, it returns a null pointer.

5. Rchild It returns a pointer to the right child of the node. If the node has no right
child, a returns a null pointer.

6. Father It returns a pointer to the father of the node. Otherwise returns the null
pointer.

7. Brother It returns a pointer to the brother of the node. Otherwise returns the null
(Sibling) pointer.

8. Data It returns the contents of the node.

Apart from these primitive operations, other operations that can be applied to the binary tree are :
1. Tree traversal
2. Insertion of nodes.
3. Deletion of nodes.
4. Searching for the node

Q.11 Explain tree traversal algorithm in brief?

Ans.The traversal of a binary tree involves visiting each node in the tree exactly one. In several
applications involving a binary tree we need to go to each node in the tree systematically. In a linear list,
nodes can be visited in a systematic manner from beginning to end. However, such an order is not
possible while traversing a tree. There are many applications that essentially require traversal of binary
trees
There are three methods commonly used for binary tree traversal. These methods are
(a) Pre-order traversal
(b) In-order traversal
(c) Post-order traversal.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 57
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.12 Explain preoder traversal?


Ans. Pre-order Traversal :The algorithm to traverse a non-empty binary tree in pre-order, is given
below :

(1) Visit the root R


(2) Traverse the left sub-tree of root R in pre-order
(3) Traverse the right sub-tree of root R in pre-order.

i.e. in a pre-order traversal the root node R is visited (or processed) before traversing its left and right
sub-trees. The pre-order notion is recursive in nature, so even within the left sub-tree and right sub-tree
the above three steps are followed. The function for pre-order traversal of binary tree shown in Fig. (14)
is
void preorder(struct tree *root)
{
if(root!=NULL)
{
printf("%c\t",root->info);
preorder(root->left);
preorder(root->right);
}
}

Consider the following tree:

Fig. (14) A Binary tree

After the pre-order traversal of Fig. (14), we get

A B D E H C F G

Q.13 Explain inoder traversal?


Ans. In-Order Traversal: The algorithm to traverse a non-empty binary tree in in-order, is given
below

(1) Traverse the left sub-tree of root R in in-order.


(2) Visit the root R.
(3) Traverse the right sub-tree of root R in in-order.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 58
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

i.e., in an in-order traversal, the left sub-tree is traversed recursively in in-order before visiting the root
node. After visiting the root node, the right sub-tree is taken up and it is traversed recursively again in
in-order. The function for in-order traversal of binary tree shown in Fig. (14) is

void inorder(struct tree *root)


{
if(root!=NULL)
{
inorder(root->left);
printf("%c\t",root->info);
inorder(root->right);
}
}

The function inorder( ) is called to traverse the tree in in-order traversal. This function receives only
one parameter *root as the address of the root node. Then a condition is checked whether the pointer if
NULL. If the pointer is not NULL, then a recursive call is made first for the left child and then for the
right child. The values passed are the addresses of the left and right children that are present in the
pointers left and right respectively. In-between these two calls the data of the current node is printed by
root->info.
Consider the following tree:

Fig. (14) A Binary tree

After the in-order traversal of Fig. (14), we get

D B H E A F C G

Q.14 Explain postoder traversal?


Ans. Post-order Traversal :The algorithm to traverse a non-empty binary tree in post-order, is given
below :

(1) Traverse the left sub-tree of root R in in-order.


(2) Traverse the right sub-tree of root R in in-order.
(3) Visit the root R.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 59
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

i.e., in a post-order traversal, the left and the right sub-tree are recursively processed before visiting the
root. The left sub-tree is taken up first and is traversed in post-order. Then the right sub-tree is taken up
and is traversed in post-order. Finally, the data of the root node is displayed. The function for in-order
traversal of binary tree shown in Fig. (14) is

void postorder(struct tree *root)


{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
printf("%c\t",root->info);
}
}
Consider the following tree:

Fig. (14) A Binary tree

After the post-order traversal of Fig. (14),

we get D H E B F G C A

Q15 Consider the binary Tree T shown in Fig. (15). Traverse it using,
(a) Preorder Traversal
(b) Inorder Traversal
(c) Postorder Traversal

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 60
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Ans.
(a) The preorder traversal of T processes A, traverses LT and traverses RT. However, the preorder
traversal of LT processes the root B and then D and E, and the preorder traversal of RT processes
the root C and then F. Hence,

Preorder Traversal : A B D E C F
(b) The inorder traversal of T traverses LT, processes A and traverses RT. However, the inorder
traversal of LT processes D, B and then E, and the inorder traversal of RT processes C and then
F. Hence,

Inorder Traversal : D B E A C F
(c) The postorder traversal of T traverses LT, traverses RT and then A. However, the postorder
traversal of LT processes D, E and then B, and the postorder traversal of RT processes F and
then C. Hence,

Postorder Traversal : D E B F C A

Q.16 Consider the binary Tree T shown in Fig. (16). Traverse it using,

(a) Preorder Traversal


(b) Inorder Traversal
(c) Postorder Traversal

Ans.
(a) The preorder traversal of T processes A, traverses LT and traverses RT. However, the preorder
traversal of LT processes the root B, D, E & H, and the preorder traversal of RT processes the
root C, F & G. Hence,

Preorder Traversal : A B D E H C F G

(b) The inorder traversal of T traverses LT, processes A and traverses RT. However, the inorder
traversal of LT processes D, B, H & E, and the inorder traversal of RT processes F, C & G.
Hence,

Inorder Traversal : D B H E A F C G

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 61
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

(c) The postorder traversal of T traverses


postorder traversal of LT processes D, E
processes F and then C. Hence,
Postorder Traversal : D H E B F G C A

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 62
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

Q.16 Example 3 : Consider the binary Tree T shown in Fig. (17). Traverse it using,

(a) Preorder Traversal


(b) Inorder Traversal
(c) Postorder Traversal

Fig. (17)

Ans.
(a) The preorder traversal of T processes A, traverses LT and traverses RT. However, the preorder
traversal of LT processes the root B, D, E & F and the preorder traversal of RT processes the root
C, G, H, J, L & K. Hence,

Preorder Traversal : A B D E F C G H J L K
(b) The inorder traversal of T traverses LT, processes A and traverses RT. However, the inorder
traversal of LT processes D, B, F & E, and the inorder traversal of RT processes G, C, L, J, H &
K. Hence,

Inorder Traversal : D B F E A G C L J H K
(c) The postorder traversal of T traverses LT, traverses RT and then A. However, the postorder
traversal of LT processes D, F, E & B, and the postorder traversal of RT processes G, L, J, K, H
& C. Hence,

Postorder Traversal : D F E B G L J K H C A

Q.17 A binary Tree T has 9 nodes. The inorder and preorder traversals results into following
sequences of nodes :
Inorder : E A C K F H D B G
Preorder : F A EKCDHGB
Draw the tree T.

Sol. The tree T is drawn from its root downward as follows :


(a) The root of T is obtained by choosing the first node in its preorder. Thus F is the root of T.

(b) The left child of the node F is obtained as follows. First use the inorder of T to find the nodes in
the left subtree LT of F. Thus LT consists of the nodes E, A, C and K. Then the left child of F is
obtained by choosing the first node in the preorder of LT (which appears in the preorder of T).
Thus A is the left son of F.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 63
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

(c) Similarly, the right subtree T2 of F consists of the nodes H, D, B & G, and D is the root of R T.
Thus, D is the right son of F.

Repeating the above process with each node, we finally obtain the required tree in
Fig.(18 ).

Q.18 Explain threaded binary tree

Ans. In the Linked representation of a Binary Tree 'T' approximately half of the entries in
the pointer fields Left and Right contain null elements. This space may be more
efficiently used by replacing the null entries with special pointers which points to nodes
higher in the tree. These special pointers are called Threads, and 'T' with such pointers
are called Threaded Trees.
Tress can be threaded using -
1. One Way Threading :
In this method, a thread will appear in the right field of a node and will point to the
successor node in the inorder traversal of tree.

2. Two Way Threading :


In this method, a thread will appear in the left field of a node and will point to the
precedding node in the inorder traversal of tree.

Q.19 Explain Huffman algorithm


Ans.
1. Suppose there are 'n' weights w 1 , w 2 , --- , w n .
2. Take 2 minimum weights among the 'n' given inputs. Suppose w 1 , w 2 are first two
minimum, then the subtree will be
3. Now the remaining weights will be w 3 , w 1 + w 2 , ---, w n .
4. Create all subtree till the last weight. Thus Huffman algorithms construct the tree
from the bottom up approach rather than top down approach.

Eg:
A B C D E
7 9 11 14 18

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 64
2018-19 [KRISHNA INSTITUTE OF TECHNOLOGY]

So coding for C=00, D=01, A=100, B=101, E=11

Application of Huffman Algorithm

The Huffman algorithm is used to perform the encoding and decoding of a long message
consisting of a set of symbols.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 65
KRISHNA INSTITUTE OF TECHNOLOGY

UNIT 4
 Graphs: Terminology
 Sequential and linked Representations of Graphs
 Adjacency Matrices
 Adjacency List
 Adjacency Multi list
 Graph Traversal : Depth First Search and Breadth First Search
 Connected Component
 Spanning Trees
 Minimum Cost Spanning Trees: Prims and Kruskal algorithm.
 Shortest Path algorithm: Warshal Algorithm and Dijikstra Algorithm

Page 66
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.1 Define graph?

Ans. Graph is a non linear data structure, it contains a set of points known as nodes (or vertices)
and set of linkes known as edges (or Arcs) which connets the vertices.
A graph is defined as follows:

 Graph is a collection of vertices and arcs which connects vertices in the graph
or
 Graph is a collection of nodes and edges which connects nodes in the graph

A Graph 'G' is a collection of two set V and E where vertices are denoted as v0, v1... vn-1 and
collection of edges e0, e1... en where V(G) is set of vertices, E(G) is set of edges and graph G
can be represented as G(V,E).

Example
The following is a graph with 5 vertices and 6 edges.
This graph G can be defined as G = ( V , E )
Where V = {A,B,C,D,E} and E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}.

Vertex;

A individual data element of a graph is called as Vertex. Vertex is also known as node. In above
example graph, A, B, C, D & E are known as vertices.

Edge:

An edge is a connecting link between two vertices. Edge is also known as Arc. An edge is
represented as (startingVertex, endingVertex). For example, in above graph, the link between
vertices A and B is represented as (A,B). In above example graph, there are 7 edges (i.e., (A,B),
(A,C), (A,D), (B,D), (B,E), (C,D), (D,E)).

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 67
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.2 Explain different types of graph and terminology used in graph ?

Ans. U n d i r e c t e d G r a p h : If the pair of vertices are unordered i.e if the edges


joining 2 vertices are not with an arrow, then the graph is called Undirected i.e
(V 1 , V 2 ) or (V 2 , V 1 ) refers the same edge.

D i r e c t e d G r a p h : If the pair of vertices are ordered i.e if the edges joining 2


vertices are with an arrow, then the graph is called Directed or Diagraph i.e (V 1 ,
V 2 ) and (V 2 , V 1 ) refers to the different edge.

W e i g h t e d G r a p h : A Graph is said to be weighted if all the edges in it are


labelled with some numbers and this number is known as the weight of the edge.

S e l f L o o p : If there is an edge whose starting and ending vertices are same i.e
(V 1 , V 1 ) is an edge then it is called Self Loop.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 68
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

P a r a l l e l E d g e s : I f there are more than 1 edge between the same pair of vertices,
then they are known as Parallel Edges.

A d j a c e n t V e r t i c e s : A vertex 'u' is adjacent to (or the neighbour of) other


vertex 'v' if there is an edge from u -> v.

D e g r e e o f a V e r t e x : The degree of a vertex is the number of edges incident on


that vertex. In an Undirected Graph, the number of edges connected to a node is
called the degree of a node. In a Diagraph, there are 2 types of degrees for every
node :

 Indegree : It is the number of edges coming to that vertex or in other words


edges incident to it.
 Outdegree : It is the number of edges goin g outside from that node or the
edges incident from it.

M u l t i g r a p h : A Graph which has either a self loop or parallel edges or both is


called MultiGraph.

C o m p l e t e G r a p h : A Graph is said to be complete graph if each vertex is


adjacent to every other vertex in graph or we can say that there is an edge between
any pair of nodes in the graph. An Undirected complete graph will contain [n(n -
1)/2] number of edges, where n is number of vertices.

C o n n e c t e d G r a p h : In a Graph, 2 vertices V 1 and V 2 are said to be both


connected if there is a path G from V 1 and V 2 or V 2 and V 1 i.e if there is a path
from any node of graph to any other node i.e for every pair of distinct vertices in
G there is a path. Example : Complete Graph

P a t h : A Path is a sequence of distinct vertices each adjacent to the next. The


length of a path is the number of edges on it.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 69
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

C y c l e : A Cycle is a path containing atleast one or more edge which starts from a
vertex and terminates into the same vertex is called Cyclic Graph.

Bridge : If on removing an edge from the graph, the graph becomes disconnected then that edge
is called the Bridge.

Q.3 Explain the Sequential representation of the graph?

Ans. Sequential representation of Binary Tree:

Let us consider that we have a tree T. let our tree T is a binary tree that us complete binary tree.
Then there is an efficient way of representing T in the memory called the sequential
representation or array representation of T. This representation uses only a linear array TREE as
follows:

1. The root N of T is stored in TREE [1].


2. If a node occupies TREE [k] then its left child is stored in TREE [2 * k] and its right
child is stored into TREE [2 * k + 1].

For Example:
Consider the following Tree:

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 70
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Its sequential representation is as follow:

Q.4 Explain the Link representation of the graph?


Ans.
Consider a Binary Tree T. T will be maintained in memory by means of a linked list
representation which uses three parallel arrays; INFO, LEFT, and RIGHT pointer
variable ROOT as follows. In Binary Tree each node N of T will correspond to a location k such
that
1. LEFT [k] contains the location of the left child of node N.
2. INFO [k] contains the data at the node N.
3. RIGHT [k] contains the location of right child of node N.

Representation of a node:
In this representation of binary tree root will contain the location of the root R of T. If any one of
the subtree is empty, then the corresponding pointer will contain the null value if the tree T itself
is empty, the ROOT will contain the null value.

Example
Consider the binary tree T in the figure. A schematic diagram of the linked list representation
of T appears in the following figure. Observe that each node is pictured with its three fields, and
that the empty subtree is pictured by using x for null entries.
Binary Tree

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 71
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Linked Representation of the Binary Tree

Q.5 Explain the following:


1. Adjacency Matrix
2. Adjacency List

Ans. 1. Adjacency Matrix:

In this representation, graph can be represented using a matrix of size total number of vertices by
total number of vertices. That means if a graph with 4 vertices can be represented using a matrix
of 4X4 class. In this matrix, rows and columns both represents vertices. This matrix is filled with
either 1 or 0. Here, 1 represents there is an edge from row vertex to column vertex and 0
represents there is no edge from row vertex to column vertex.

For example, consider the following undirected graph representation.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 72
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Directed graph representation:

2. Adjacency List :

In this representation, every vertex of graph contains list of its adjacent vertices.

For example, consider the following directed graph representation implemented using linked list.

Q. 6 Explain the DFS algorithm with the help of example

Ans.It is the traversal technique which is used whenever it is possible to search the graph deeper.
Given as input graph G = (V, E) and a source vertex S from where the searching start.

 First we travel or visit the starting node then we travel through each node along a path
which begins at Stack 'S' i.e we visit a neighbour vertex of S and again a neighbour os S
and so on.
 DFS works on both directed and undirected graph.

DFS(vertex i)
1. Initialize a stack 'S' of vertex 'w'
2. Push 'i' in the stack 'S'
3. Repeat step 4 to 5 while(stack S is not empty)

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 73
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

4. i = pop(S)
5. if(!visited[i]) then
a) visited[i] = 1
b) for each w adjacent to i
if(!visited[w]) then push w in the stack S
6. Return

1. Initially, push J onto the stack as follows :


STACK : J

2. Pop J and push onto stack all the neighbours of J


STACK : D, K

3. Pop top element K and push onto stack all the neighbours of K
STACK : D, E, G

4. Pop top element G and push onto stack all the neighbours of G
STACK : D, E, C

5. Pop top element C and push onto stack all the neighbours of C
STACK : D, E, F

6. Pop top element F and push onto stack all the neighbours of F
STACK : D, E

7. Pop top element E and push onto stack all the neighbours of E

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 74
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

STACK : D

8. Pop D and push onto stack all the neighbours of D


STACK : ∅

The nodes which were printed are: J,K,G,C,F,E,D

Q.7 Explain BFS algorithm with the help of example?


Ans. It is the technique which uses queue for traversing all the nodes of the graph.

 In this, first we take any node as the starting node then we take all the adjacent nodes to
that starting node. Similarly, we take for all other adjacent nodes and so on.

 We maintain the status of visited nodes in an array so that no node can be traversed again.
BFS also works on directed and undirected graphs.

BFS(vertex V)
1. Initialize a Queue Q
2. Add V to Queue Q
3. Set visited[V] = 1
4. Repeat step 5 to 6 while(Q is not empty)
5. Delete the element V from Q
6. for all vertices w adjacent from V
a) if(!visited[w]) then
set visited[w] = 1 and add vertex w to the Q
7. Return
Example of BFS

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 75
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

1. Consider the above figure. Initially, add A to Queue and add Null to ORIG array
as follows :
QUEUE : A
ORIG : ∅

2. Remove A from Queue and add neighbours of A to Queue


QUEUE : F, C, B
ORIG : A

3. Remove first element F rom Queue and add neighbours of F to Queue


QUEUE : C, B, D
ORIG : A, F

4. Remove first element C rom Queue and add neighbours of C to Queue


QUEUE : B, D
ORIG : A, F, C

5. Remove first element B rom Queue and add neighbours of B to Queue


QUEUE : D, G
ORIG : A, F, C, B

6. Remove D rom Queue and add neighbours of D to Queue


QUEUE : G
ORIG : A, F, C, B, D

7. Remove G rom Queue and add neighbours of G to Queue


QUEUE : E
ORIG : A, F, C, B, D, G

8. Remove E rom Queue and add neighbours of E to Queue


QUEUE : J
ORIG : A, F, C, B, D, G, E

9. Remove J rom Queue and add neighbours of J to Queue


QUEUE : ∅
ORIG : A, F, C, B, D, G, E, J

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 76
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.7 Define the term spanning tree?

Ans. A spanning tree is a subset of Graph G, which has all the vertices covered with minimum
possible number of edges. Hence, a spanning tree does not have cycles and it cannot be
disconnected..

By this definition, we can draw a conclusion that every connected and undirected Graph G has at
least one spanning tree. A disconnected graph does not have any spanning tree, as it cannot be
spanned to all its vertices.

We found three spanning trees off one complete graph. A complete undirected graph can have
maximum nn-2 number of spanning trees, where n is the number of nodes. In the above
addressed example, n is 3, hence 33−2 = 3 spanning trees are possible.

Q.8 Explain Minimum Spanning tree?

Ans. Given a connected weighted Graph 'G', it is often desired to create a spanning tree 'T' for 'G'
such that the sum of the weights of the tree edges in 'T' is as small as possible. Such a tree which
is formed with least possible cost is called Minimum Cost Spanning Tree and connects all the
nodes in G.

Some of the methods for creating a minimum cost spanning tree for a weighted graph is -

 Prim's Algorithm
 Kruskal's Algorithm

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 77
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.9 Write down the algorithm for Prim’s spanning tree with the help of example.
Ans.
The following are the main 3 steps of the Prim's Algorithm:

1. Begin with any vertex which you think would be suitable and add it to the tree.
2. Find an edge that connects any vertex in the tree to any vertex that is not in the tree. Note
that, we don't have to form cycles.
3. Stop when n - 1 edges have been added to the tree.

Q.10 Write down the algorithm for Kruskal’s spanning tree with the help of example.

Ans Kruskal’s algorithms is one of the types of greedy algorithms which is used to solve a
minimal spanning tree (MST) by choosing the best possible choice at each step and then, this
decision leads to the best over all solution.

The main steps of the Kruskal's Algorithm are as follows:

1. Arrange the edges by weight: least weight first and heaviest last.
2. Choose the lightest not examined edge from the diagram. Add this chosen edge to the
tree, only if doing so will not make a cycle.
3. Stop the process whenever n - 1 edges have been added to the tree.

For example :

Solution:
The list of edges in order of their weights or sizes would be as follows:

Edge Weight Edge Weight


ED 2 EF 5
AB 3 CF 6
AE 4 AF 7
CD 4 BF 8
BC 5 CF 6

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 78
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

The various iterations would be as follows:

All the vertices have been connected now, hence, the last iteration number 5, gives us the
optimal solution, and the minimum length would be the sum of all weights given to these edges,
as 2 + 3 + 4 + 4 + 5 = 18 is the length of the shortest path by applying Kruskal's Algorithm.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 79
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

That is, the solution is


ED 2
AB 3
CD 4
AE 4
EF 5,
with Total weight of tree equal to 18

Q.11 Write down the Dijikstra algorithm for finding out the shortest path in the graph.

Ans.Dijkstra’s algorithm solves the single-source shortest-paths problem on a directed weighted


graph G = (V, E), where all the edges are non-negative (i.e., w(u, v) ≥ 0 for each edge (u, v) Є E).

The complexity of this algorithm is fully dependent on the implementation of Extract-Min


function. If extract min function is implemented using linear search, the complexity of this
algorithm is O(V2 + E).

Let us consider vertex 1 and 9 as the start and destination vertex respectively. Initially, all the
vertices except the start vertex are marked by ∞ and the start vertex is marked by 0.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 80
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Step1 Step2 Step3 Step4 Step5 Step6 Step7 Step8


Vertex Initial
V1 V3 V2 V4 V5 V7 V8 V6

1 0 0 0 0 0 0 0 0 0

2 ∞ 5 4 4 4 4 4 4 4

3 ∞ 2 2 2 2 2 2 2 2

4 ∞ ∞ ∞ 7 7 7 7 7 7

5 ∞ ∞ ∞ 11 9 9 9 9 9

6 ∞ ∞ ∞ ∞ ∞ 17 17 16 16

7 ∞ ∞ 11 11 11 11 11 11 11

8 ∞ ∞ ∞ ∞ ∞ 16 13 13 13

9 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ 20

Hence, the minimum distance of vertex 9 from vertex 1 is 20. And the path is

1→ 3→ 7→ 8→ 6→ 9

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 81
KRISHNA INSTITUTE OF TECHNOLOGY

UNIT 5
 Searching: Sequential search, Binary Search
 Comparison and Analysis Internal Sorting
 Insertion Sort
 Selection
 Bubble Sort
 Quick Sort
 Heap Sort
 Radix Sort
 Binary Search Trees (BST)
 Insertion and Deletion in BST
 Complexity of Search Algorithm
 AVL trees
 Introduction to m-way Search Trees
 B Trees & B+ Trees

Page 82
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.1 Define Searching ?

Ans. Searching is an operation which finds the location of a given element in the list. The search is said
to be successful or unsuccessful depending on whether the element that is to be searched is found or not.
There are mainly two standard searching methods, which are commonly used

1. Linear Search

2. Binary Search

Q.2 Explain linear search?

Ans. This is the simplest method of searching. In this method, the element to be found is sequentially
searched in the list. This method can be applied to a sorted or an unsorted list.

 Searching in case of a sorted list starts from 0th element and continues until the element is found
or an element whose value is greater (assuming the list is sorted in ascending order) than the value
being searched is reached.
 Searching in case of unsorted list starts from the 0th element and continues until the element is
found or the end of the list is reached.

To understand this, consider the array shown in Fig. In which we are required to search a
number 57 in an unsorted arrray.

 The array shown in Fig consists of 10 numbers. Suppose the element that is to be searched is 57.
So 57 is compared with all the elements started with 0th element and the searching process ends
either when 57 is found or the lists ends.
 The performance of linear search algorithm can be measured by counting the comparisons done to
find out an element. The number of comparisons is O (n).
In case of sorted list, searching of element starts from the 0 th element. Searching ends when the
element is found or any element of the list is found to be greater than the element to be
searched. This is shown in Fig. (1).

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 83
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.3 Write down the algorithm for linear search?

Ans. Let A[n] is an array of n elements and NUM is the number to be searched in array, I is the index
number of each array element.

1. Set F = 0.
2. Read n elements of array A.
3. Read number NUM to be searched in Array A.
4. Repeat Step 4 for I = 0 to n :
If NUM = A[ I ] then :
Set F = 1
BREAK;
[End of If Structure]
[End of Step 4 loop].
5. If F = 0 then :
Write ‘Number is not present in array’
Else
Write ‘Number is present in array at location -‘,I+1
[End of If Else Structure].
6. Exit

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 84
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.4 Explain binary search?

Ans. Binary search method is very fast and efficient. This method requires that the list of elements be in
sorted order.

 In this method, to search an element we compare it with the element present at the center of the
list. If it matches then the search is successful. Otherwise, the list is divided into two halves: one
from 0th element to the center element (first half), and another from center element to the last
element (second half). As a result, all the elements in first half are smaller than the center
element, whereas, all the elements in second half are greater than the center element.

 The searching will now proceed in either of the two halves depending upon whether the element
is greater or smaller than the center element. If the element is smaller than the center element
then the searching will be done in the first half, otherwise in the second half.

 Same process of comparing the required element with the center element and if not found then
dividing the elements into two halves is repeated for the first half or second half. This procedure
is repeated till the element is found or the division of half parts gives one element. Let us
understand this with the help of Fig(3).

Suppose an array arr consists of 10 sorted numbers and 57 is element that is to be searched. The binary
search method when applied to this array works as follows :

1. 57 is compared with the element present at the center of the list (i.e. 11). Since 57 is greater than
11, the searching is restricted only to the second half of the array.
2. Now 57 is compared with the center element of the second half of array (i.e. 25). Here, again 57 is
greater than 25 so the searching now proceed in the elements present between the 25 and the last
element 90.
3. This process is repeated till 57 is found or no further division of sub-array is possible.

The maximum number of comparisons in binary search is limited to log2 n.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 85
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.5 Write down the algorithm for binary search.


Ans. Let A[10] is an array of 10 elements and NUM is the number to be searched in array, L
represents the lower bound, U represents the upper bound and M represents the index number of
middle element, I represents the index number of each array element.

(1) Set F = 0, L = 0, U = 9.
(2) Read 10 elements of array A in ascending order.
(3) Read number NUM to be searched in Array A.
(4) Repeat Step 4 while L ≤ U
Set M = (L + U) / 2.
If NUM > A[M] : then
Set L = M +1
Else If NUM < A[M] : then
Set U = M – 1
Else
Set F = 1
BREAK.
[End of If Else If Structure]
[End of Step 4 loop].
5. If F = 0 : then
Write ‘Number is not present in Array’.
Else
Write ‘Number is present in Array at position–‘, M + 1.
[End of If Else Structure]
6. Exit

Q.6 Compare the linear search and binary search algorithm.

Ans.Consider the following set of elements : 1, 2, 3, 9, 11, 13, 17, 25, 57, 90

Suppose, we want to search 25 in the above set of numbers. Table (1) shows number of
comparisons required in both the methods.

Method Number of comparisons


Linear Search 8
Binary Search 3

The table clearly shows that how fast a binary search algorithm works.

 The advantage of the binary search method is that, in each iteration, it reduces the
number of elements to be searched from n to n/2. On the other hand, linear search
method checks sequentially for every element, which makes it inefficient.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 86
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

 The disadvantage of binary search is that it works only on sorted lists. So when
searching is to be performed on unsorted list then linear search is the only option.

Q.7 Explain the term sorting?

Ans. Sorting means arranging a set of data in some order. There are different methods that are
used to sort the data in ascending or descending order. These methods can be divided into two
categories. They are as follows :

1. External Sorting
2. Internal Sorting
Q.8 Define the term external sorting?
Ans. When the data to be sorted is so large that some of the data is present in the memory and
some is kept in auxiliary memory (hard disk, floopy, tape etc), then external sorting methods are
used. External sorting is applied to the huge amount of data that cannot be accommodate in the
memory all at a time. So data from the disk is loaded into memory part by part and each part that
is loaded is sorted and the sorted data is stored into some intermediate file. Finally all the sorted
parts present in different intermediate file. Finally all the sorted parts present in different
intermediate files are merged into one single file.

Q.9 Define the term internal sorting?


Ans. If all the data that is to be sorted can be accommodated at a time in memory then internal
sorting methods are used.

There are different types of internal sorting methods. The following methods sort the data in
ascending order. With a minor change, we can also sort the data in descending order. Some
standard methods are as given below :

1. Selection Sort

2. Bubble Sort

3. Insertion Sort
4. Quick Sort
5. Merge Sort

6. Radix Sort

7. Heap Sort

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 87
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.10 Explain the concept of selection sort.


Ans. This is the simplest method of sorting. In this method, to sort the data in ascending order,
the 0th element is compared with all other elements. If the 0th element is found to be greater than
the compared element then they are interchanged. So after the first iteration, the smallest element
is placed at 0th position. The same procedure is repeated for the 1st element and so on. This can
be explained with the help of Fig.
Suppose an array arr consists of 5 numbers. The selection sort algorithm work as follows :
th st
 In the first iteration, the 0 element 25 is compared with 1 element 17 and since 25 is
greater than 17, they are interchanged.
th nd
 Now the 0 element 17 is compared with 2 element 31. But 17 being less than 31, hence
they are not interchanged.
th
 This process is repeated till 0 element is compared with rest of the elements. During the
th
comparison if 0 element is found to be greater than the compared element, then they are
interchanged, otherwise not.
th
 At the end of the first iteration, the 0 element holds the smallest number.
st
 Now the second iteration starts with the 1 element 25. The above process of comparison and
swapping is repeated.
 So if there are n elements, then after (n – 1) iterations, the array is sorted.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 88
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.11 Write down the algorithm for selection sort.

Ans. Let A[5] is an array of 5 elements and TEMP is the variable used for swapping of array
elements.

1. Read 5 elements of array A.


2. Write Original Array A.
3. Repeat Steps 3 to 4 for I = 0 to 3.
4. Repeat Step 4 for J = I+1 to 4.
IF A[I] > A[J] : then [Interchange A[I] & A[J]]
Set TEMP = A[J].
Set A[J] = A[I]

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 89
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Set A[I] = TEMP


[End of IF structure].
[End of Step 4 loop].
[End of Step 3 loop].
5. Write Sorted Array A.
6. Exit

Q.12 Explain the concept of bubble sort.

Ans. In this method, to arrange elements in ascending order, to begin with the 0th element is
compared with the 1st element.
 If it is found to be greater than the 1st element then they are interchanged. Then the 1st
element is compared with the 2nd element, if it is found to be greater, then they are
interchanged.
 In the same way all the elements( excluding list) are compared with their element and are
interchanged if required.
 This is the first iteration and on completing this iteration the largest element gets placed
at the last position. Similarly, in the second iteration the comparisons are made till the
last but one element and this time the second largest element gets placed at the second
last position in the list. As a result, after all the iterations the list becomes a sorted list.
 This can be explained with the help of Fig.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 90
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.13 Explain insertion sort?

Ans. Insertion sort is implemented by inserting a particular element at the appropriate position.
st i th
 In this method, the first iteration starts with comparison of 1 eleme nt with the 0 element.
nd th st
In the second iteration, 2 element is compared with the 0 and 1 element.
 In general, in every iteration an element is compared with all elements before it.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 91
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

 During comparison, if is found that the element in question can be inserted at a suitable
position then space is created for it by shifting the other element at the suitable position.
 This procedure is repeated for all the elements in the array. Let us understand this with the
help of Fig.

Following steps explain the algorithm of insertion sort for an array A of 5 elements.

(a) In the first iteration, the 1st element 17 is compared with the 0th element 25. Since 17 is
smaller than 25, 17 is inserted at 0th place. The 0th element 25 is shifted one position to
the right.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 92
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

(b) In the second iteration, the 2nd element 31 and thend0th element 17 are compared. Since 31st
is greater than 17, nothing is done. Then the 2 element 31 is compared with the 1
element 25. Again no action is taken as 25 is less than 31.

(c) In the third iteration, the 3rd element 13 is compared with the 0th element 17. Since, 13 is
smaller than 17, 13 is inserted at the 0th place in the array and all the element from 0th till
2nd position are shifted to right by one position.

(d) In the fourth iteration, the 4th element 2 is compared with the 0th element 13. Since, 2 is
element smaller than 13, the 4th is inserted at the 0th place in the array and all the are
shifted right by elements from 0th till 3rd one position. As a result, the array now
becomes a sorted Array.

Q.14 Write down the algorithm for insertion sort?

Ans.Let A [5] is an array of 5 elements and TEMP is the variable used for storing the number to
be inserted at a particular position.

1. Read 5 elements of array A.


2. Write Original Array A.
3. Repeat Steps 3 to 5 for I = 1 to 4.
4. Repeat Step 4 to 5 for J = 0 to
I – 1. IF A[J] > A[I] : then
Set TEMP = A[I]
5. Repeat Step 5 for K = I to J + 1
Set A[K] = A[K-1]
[End of Step 5 loop].
[End of Step 4 IF structure].
[End of Step 4 loop].
[End of Step 3 loop].
6. Write Sorted Array A.

7. Exit

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 93
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.15 Sort the given array with the help of merge sort (15,10,5,20,25,30,4,35) ?

Ans.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 94
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.16 Explain the concept of merge sort.

Ans. Merge sort is a sorting technique based on divide and conquer technique.

 With worst-case time complexity being Ο(n log n), it is one of the most respected
algorithms.

 Merge sort first divides the array into equal halves and then combines them in a sorted
manner
Q.17 Explain the concept of heap sort?

Ans. Heap sort is a comparison based sorting algorithm.

 It is a special tree-based data structure.


 Heap sort is similar to selection sort. The only difference is, it finds largest element and
places the it at the end.
 This sort is not a stable sort. It requires a constant space for sorting a list.
 It is very fast and widely used for sorting.

The Time complexity of Heap Sort is O(nlogn).

Max Heap
A Max heap is a complete binary tree 'H' with n elements, if each node 'N' of H is
greater than equal to the children of 'N' is known as Max Heap. It is also known as
Descending Heap.

Min Heap
A Min heap is defined analogously i.e the value at 'N' is less than or equal to the
value of children of 'N'. It is also known as Ascending Heap.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 95
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Example of Heap Sort:


Construct a heap from elements 10, 15, 7, 8, 12, 20, 8, 6.
The first element is 10, make it as a Root. The next element 15 becomes left child of root and
3rdelement becomes right child of root. Repeat this untill all elements are used.

Simply insert the element from left


to right in order.

Build max heap from above heap

In right subtree, since 20 is greater than 7 and we are constructing a max heap so
interchange them and make max heap. After interchanging, still the max heap
property is not satisfied so interchange 20 and 10 also.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 96
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Now build max heap from


above heap

Interchange 20 and 7 to
Interchange 10 and 20
build max heap
to build max heap

Sort above heap using heap sorting technique.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 97
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Start Sorting

Exchange root node with last Element 20 is sorted put


node to start sorting of heap the element in the array
and again build the max
heap

Interchange 12 and 6 to Exchange 15 with 8


obtain max heap

Put the element 15 in the array


next to the previous element an
Exchange 12 with 7
again build the max heap.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 98
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.18 Write down the algorithm for heap sort.


Ans.

PARTITION (ARR, BEG, END, LOC)


Step 1: [INITIALIZE] SET LEFT = BEG, RIGHT = END, LOC = BEG, FLAG=0
Step 2: Repeat Steps 3 to 6 while FLAG =
Step 3: Repeat while ARR[LOC] <= ARR[RIGHT] AND
LOC != RIGHT SET RIGHT = RIGHT - 1
[END OF LOOP]
Step 4: IF LOC = RIGHT
SET FLAG = 1
ELSE IF ARR[LOC] > ARR[RIGHT]
SWAP ARR[LOC] with ARR[RIGHT]
SET LOC = RIGHT
[END OF IF]
Step 5: IF FLAG = 0
Repeat while ARR[LOC] >= ARR[LEFT] AND LOC != LEFT
SET LEFT = LEFT + 1
[END OF LOOP]
Step 6: IF LOC = LEFT
SET FLAG = 1
ELSE IF ARR[LOC] < ARR[LEFT]
SWAP ARR[LOC] with ARR[LEFT]
SET LOC = LEFT
[END OF IF]
[END OF IF]
Step 7: [END OF LOOP]
Step 8: END

QUICK_SORT (ARR, BEG, END)


Step 1: IF (BEG < END)
CALL PARTITION (ARR, BEG, END, LOC)
CALL QUICKSORT(ARR, BEG, LOC - 1)
CALL QUICKSORT(ARR, LOC + 1, END)
[END OF IF]
Step 2: END

Q.19 Explain the concept of radix sort?

Ans. Let 'n' be the number of elements and 'd' be the number of digit then it will require 'd' passes
to be sorted completely. So in the first pass, the elements or number are sorted on the basis of
last digit or letter in it. In the second pass, each number is arranged according to the second last
letter in it and the pass continues until the first letter is considered from the number.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 99
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

This algorithm is not suitable for large digit number as its worst case and average case
complexity are O(n), where 'n' is the number of items.

In Pass 1 : Elements are sorted on the basis of unit digit.

In Pass 2 : The output of Pass 1 is used as input for Pass 2. In Pass 2 elements are sorted on the
basis of ten's digit.

In Pass 3 : The output of Pass 2 is used as input for Pass 3. In Pass 3 elements are sorted on the
basis of hundred digit. The final list is sorted.

Sort the numbers given below using radix sort. 345, 654, 924, 123, 567, 472, 555, 808, 911
Number 0 1 2 3 4 5 6 7 8 9

345 345

654 654

924 924

123 123

567 567

472 472

555 555

808 808
911 911

Pass 2:
Number 0 1 2 3 4 5 6 7 8 9

911 911

472 472

123 123

654 654

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 100
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

924 924

345 345

555 555

567 567

808 808

Pass 3:

Numb
er 0 1 2 3 4 5 6 7 8 9

808 808

911 911

123 123

924 924

345 345

654 654

555 555

567 567

472 472

Q20. Explain binary search tree.

Ans A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned
properties −

 The left sub-tree of a node has a key less than or equal to its parent node's key.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 101
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

 The right sub-tree of a node has a key greater than to its parent node's key.

The following tree is a Binary Search Tree. In this tree, left subtree of every node contains
nodes with smaller values and right subtree of every node contains larger values.

Q22. Write down the steps for searching the element in binary search tree?

Ans.

In a binary search tree, the search operation is performed with O(log n) time complexity. The
search operation is performed as follows:

Step 1: Read the search element from the user

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 102
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Step 2: Compare, the search element with the value of root node in the tree.

Step 3: If both are matching, then display "Given node found!!!" and terminate the function

Step 4: If both are not matching, then check whether search element is smaller or larger than
that node value.

Step 5: If search element is smaller, then continue the search process in left subtree.

Step 6: If search element is larger, then continue the search process in right subtree.

Step 7: Repeat the same until we found exact element or we completed with a leaf node

Step 8: If we reach to the node with search value, then display "Element is found" and
terminate the function.

Step 9: If we reach to a leaf node and it is also not matching, then display "Element not
found" and terminate the function.

Q23. Write down the steps for inserting an element in binary search tree?

Ans

In a binary search tree, the insertion operation is performed with O(log n) time complexity. In
binary search tree, new node is always inserted as a leaf node. The insertion operation is
performed as follows.

Step 1: Create a newNode with given value and set its left and right to NULL.

Step 2: Check whether tree is Empty.

Step 3: If the tree is Empty, then set set root to newNode.

Step 4: If the tree is Not Empty, then check whether value of newNode is smaller or larger than
the node (here it is root node).

Step 5: If newNode is smaller than or equal to the node, then move to its left child. If newNode
is larger than the node, then move to its right child.

Step 6: Repeat the above step until we reach to a leaf node (e.i., reach to NULL).

Step 7: After reaching a leaf node, then insert the newNode as left child if newNode is smaller
or equal to that leaf else insert it as right child.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 103
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q24. Write down the steps for deleting an element in binary search tree?

Ans In a binary search tree, the deletion operation is performed with O(log n) time complexity.
Deleting a node from Binary search tree has follwing three cases...

Case 1: Deleting a Leaf node (A node with no children)

Case 2: Deleting a node with one child

Case 3: Deleting a node with two children

Case 1: Deleting a leaf node

We use the following steps to delete a leaf node from BST.

Step 1: Find the node to be deleted using search operation

Step 2: Delete the node using free function (If it is a leaf) and terminate the function.

Case 2: Deleting a node with one child

We use the following steps to delete a node with one child from BST.

Step 1: Find the node to be deleted using search operation

Step 2: If it has only one child, then create a link between its parent and child nodes.

Step 3: Delete the node using free function and terminate the function.

Case 3: Deleting a node with two children

We use the following steps to delete a node with two children from BST.

Step 1: Find the node to be deleted using search operation

Step 2: If it has two children, then find the largest node in its left subtree (OR) the smallest
node in its right subtree.

Step 3: Swap both deleting node and node which found in above step.

Step 4: Then, check whether deleting node came to case 1 or case 2 else goto steps 2

Step 5: If it comes to case 1, then delete using case 1 logic.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 104
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Step 6: If it comes to case 2, then delete using case 2 logic.

Step 7: Repeat the same process until node is deleted from the tree.

Q.25 Construct a Binary Search Tree by inserting the following sequence of numbers.
10, 12, 5, 4, 20, 8, 7, 15 and 13/
Ans.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 105
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.26 Explain all case with suitable example for deleting the node in BST.

Ans. Case1 : Deleting a node with no child.

Case 2: Deleting a node with one child

Case 2

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 106
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Case 3: Deleting a node with two children

Q.27 Define AVL tree?


Ans. AVL tree is a self balanced binary search tree.

 That means, an AVL tree is also a binary search tree but it is a balanced tree.
 A binary tree is said to be balanced, if the difference between the height of left and right
subtrees of every node in the tree is either -1, 0 or +1.
 In other words, a binary tree is said to be balanced if for every node, height of its
children differ by at most one.
 In an AVL tree, every node maintains a extra information known as balance factor.
 The AVL tree was introduced in the year of 1962 by G.M. Adelson-Velsky and E.M.
Landis.

 Balance factor of a node is the difference between the heights of left and right subtrees
of that node.
 The balance factor of a node is calculated either height of left subtree - height of right
subtree (OR) height of right subtree - height of left subtree.

 In the following explanation, we are calculating as follows...

Balance factor = heightOfLeftSubtree - heightOfRightSubtree

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 107
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Every AVL Tree is a binary search tree but all the Binary Search Trees need not to be
AVL trees.

Q.28 Explain AVL tree operation?

Ans. In AVL tree, after performing every operation like insertion and deletion we need to check
the balance factor of every node in the tree.
 If every node satisfies the balance factor condition then we conclude the operation
otherwise we must make it balanced.

 We use rotation operations to make the tree balanced whenever the tree is becoming
imbalanced due to any operation.

 Rotation operations are used to make a tree balanced.

 Rotation is the process of moving the nodes to either left or right to make tree balanced.

 There are four rotations and they are classified into two types.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 108
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Single Left Rotation (LL Rotation)

In LL Rotation every node moves one position to left from the current position. To understand
LL Rotation, let us consider following insertion operations into an AVL Tree.

Single Right Rotation (RR Rotation)

In RR Rotation every node moves one position to right from the current position. To understand
RR Rotation, let us consider following insertion operations into an AVL Tree.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 109
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Left Right Rotation (LR Rotation)

The LR Rotation is combination of single left rotation followed by single right rotation. In LR
Rotation, first every node moves one position to left then one position to right from the current
position. To understand LR Rotation, let us consider following insertion operations into an AVL
Tree.

Right Left Rotation (RL Rotation)

The RL Rotation is combination of single right rotation followed by single left rotation. In RL
Roration, first every node moves one position to right then one position to left from the current
position. To understand RL Rotation, let us consider following insertion operations into an AVL
Tree.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 110
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.29 Construct an AVL Tree by inserting numbers from 1 to 8.


Ans.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 111
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 112
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Q.29 Explain the term BTree?

Ans.B-Tree can be defined as follows.

 B-Tree is a self-balanced search tree with multiple keys in every node and more than two
children for every node.

 Here, number of keys in a node and number of children for a node is depend on the order
of the B-Tree. Every B-Tree has order.

B-Tree of Order m has the following properties...

 Property #1 - All the leaf nodes must be at same level.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 113
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

 Property #2 - All nodes except root must have at least [m/2]-1 keys and maximum of m-
1 keys.
 Property #3 - All non leaf nodes except root (i.e. all internal nodes) must have at least
m/2 children.
 Property #4 - If the root node is a non leaf node, then it must have at least 2 children.
 Property #5 - A non leaf node with n-1 keys must have n number of children.
 Property #6 - All the key values within a node must be in Ascending Order.

For example, B-Tree of Order 4 contains maximum 3 key values in a node and maximum 4
children for a node.

Example:

Q.30 Explain the insertion operation in B Tree?

Ans. In a B-Tree, the new element must be added only at leaf node. That means, always the
new keyValue is attached to leaf node only. The insertion operation is performed as follows.

Step 1: Check whether tree is Empty.


Step 2: If tree is Empty, then create a new node with new key value and insert into the tree as a
root node.
Step 3: If tree is Not Empty, then find a leaf node to which the new key value cab be added
using Binary Search Tree logic.
Step 4: If that leaf node has an empty position, then add the new key value to that leaf node by
maintaining ascending order of key value within the node.

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 114
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Step 5: If that leaf node is already full, then split that leaf node by sending middle value to its
parent node. Repeat the same until sending value is fixed into a node.
Step 6: If the splitting is occurring to the root node, then the middle value becomes new root
node for the tree and the height of the tree is increased by one.

Q.31 Construct the B Tree of order 3 inserting an element number from 1 to 10.

Ans. Step 1: Insert 1

Step 2: Insert 2

Step 3: Insert 3

Step 4: Insert 4

Step 5: Insert 5

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 115
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Step 6: Insert 6

Step 7: Insert 7

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 116
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

Step 8: Insert 8

Step 9: Insert 9

Step 10: Insert 10

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 117
2018-19 [ KRISHNA INSTITUTE OF TECHNOLOGY]

RUCHI KHETAN
ASST PROFESSOR CSE DEPTT
Page 118

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy