100% found this document useful (1 vote)
1K views75 pages

DSL Lab Manual

The document is a preface to a lab manual for a Data Structures and Algorithms laboratory course. It introduces some key concepts about data structures and algorithms. It provides that data structures are used to store and organize data to allow for efficient use, processing, retrieval, and storage of data. Algorithms are step-by-step procedures to solve problems. The lab manual will cover various data structures and algorithms including hashing, trees, graphs, search trees, and file organization. It was prepared by faculty in the Department of Computer Engineering at Marathwada Mitra Mandal's College of Engineering, Pune.

Uploaded by

Soham
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views75 pages

DSL Lab Manual

The document is a preface to a lab manual for a Data Structures and Algorithms laboratory course. It introduces some key concepts about data structures and algorithms. It provides that data structures are used to store and organize data to allow for efficient use, processing, retrieval, and storage of data. Algorithms are step-by-step procedures to solve problems. The lab manual will cover various data structures and algorithms including hashing, trees, graphs, search trees, and file organization. It was prepared by faculty in the Department of Computer Engineering at Marathwada Mitra Mandal's College of Engineering, Pune.

Uploaded by

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

Marathwada Mitra Mandal's

COLLEGE OF ENGINEERING, PUNE


Accredited with 'A++' Grade by NAAC,
Recipient of “Best College Award 2019” by SPPU,
Accredited Mechanical and Electrical Departments by NBA

Department of Computer Engineering

Lab Manual

210256 : Data Structure and Algorithms Laboratory

Prepared by,

Mrs. Shubhada Mone


Mrs. Swarupa Deshpande
Ms. Aishwarya Mane
Mrs. Mayuri Narkhede

SE COMP (2019 Pattern)

Academic Year 2023-24 Sem II


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

Preface

Data Structures are the programmatic way of storing data so that data can be used efficiently. Almost every
enterprise application uses various types of data structures in one or the other way. A data structure is not
only used for organizing the data. It is also used for processing, retrieving, and storing data. There are
different basic and advanced types of data structures that are used in almost every program or software system
that has been developed. So we must have good knowledge about data structures.Algorithm is a step-by-step
procedure, which defines a set of instructions to be executed in a certain order to get the desired output.
Algorithms are generally created independent of underlying languages, i.e. an algorithm can be implemented
in more than one programming language.

These extensive system studies include:


Hashing
Trees
Graphs
Search Trees
Indexing and Multi-way Trees
File Organization

Department of Computer Engineering, MMCOE, Pune


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

Department of Computer Engineering, MMCOE, Pune


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

Department of Computer Engineering, MMCOE, Pune


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

Program Outcomes (POs)

Engineering Graduates will be able to:

1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering fundamentals


and an engineering specialization to the solution of complex engineering problems.
2. Problem Analysis: Identify, formulates, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
3. Design / development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research – based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
5. Modern tool usage: Create, select and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

Department of Computer Engineering, MMCOE, Pune


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

Rubrics for Lab Assessment (CAS)

Scale
Dimension
1 2 3 4 5

Did not Performed and Performed on Performed on


Performed and
Regularity and Perform, submitted schedule; schedule;
submitted as
punctuality submitted in later than submitted two submitted one
per schedule
time scheduled date weeks late week late

Neither
shows any Can only state Understands Understands
Understanding and understandin States the the objective objective but objective and
preparation for g of the objective very but shows cannot place it can relate it to
Objective objective nor vaguely poor in context of a an appropriate
can relate it understanding theory theory topic
to theory.
Performs
Performs the
experiment on
Performs the experiment Performs
his/her own
experiment with some experiment on
without
Participation in only with the supervisory own without
Does not supervisory
performance and help from help; but supervisory
participate in help; records
conduction of supervisor/oth forgets some help; records
experiment all readings
experiment ers and is crucial reading all readings
properly.
confused and and is properly but
Keeps the
untidy. confused and untidy.
setup clean
untidy.
and tidy.
Follows right
Cannot Follows right Follows right
procedure; can
follow the Follows procedure; but procedure and
analyze data
Post experiment skills procedure procedure cannot analyze can analyze
and interpret it
and do any half-heartedly data and data and
with
work interpret it interpret it
justification

Department of Computer Engineering, MMCOE, Pune


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

Syllabus

Department of Computer Engineering, MMCOE, Pune


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

Department of Computer Engineering, MMCOE, Pune


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

Department of Computer Engineering, MMCOE, Pune


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

A. Course Outcome

Statement BTL
Course
Outcome
At the end of the course, a student will be able to

210256.1 Understand the ADT/libraries, hash tables and dictionary to design BTL1
algorithms for a specific problem.

210256.2 Apply the most appropriate data structures for graphical solutions of the BTL3
problems.

210256.3 Apply non linear data structures to solve real world complex problems. BTL3

210256.4 Understand the efficiency of the most appropriate data structure while BTL1
creating efficient solutions for engineering design situations.

B. CO-PO mapping

Program outcomes
Course
Outcome
1 2 3 4 5 6 7 8 9 10 11 12

210256.1 - 1 - - - - - - - - - -

210256.2 2 1 - - - - - - - - - -

210256.3 2 1 - 1 - - - - - - - -

210256.4 - 1 - 1 - - - - - - - -

Department of Computer Engineering, MMCOE, Pune


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

CO-PSO mapping

Program Specific Outcomes


Course Outcome
1 2

210256.1 - 1

210256.2 - 1

210256.3 - 1

210256.4 - 1

Department of Computer Engineering, MMCOE, Pune


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

INDEX

Sr. Group Title of Lab Assignment CO PO


No.

CO PO2,
1 Consider a telephone book database of N clients. Make use of a hash 1 PSO2
table implementation to quickly look up client‘s telephone number.
A Make use of two collision handling techniques and compare them using
number of comparisons required to find a set of telephone numbers
(Python)

CO PO2,
2 Implement all the functions of a dictionary (ADT) using hashing 1 PSO2
and handle collisions using chaining with / without replacement.
Data: Set of (key, value) pairs, Keys are mapped to values, Keys
must be comparable, Keys must be unique Standard Operations:
Insert(key, value), Find(key), Delete(key) (python)

CO PO2,
3 A book consists of chapters, chapters consist of sections and sections 1 PSO2
consist of subsections. Construct a tree and print the nodes. Find the
time and space requirements of your method.

PO1,
4 B Beginning with an empty binary search tree, Construct a binary search CO2 PO2,
tree by inserting the values in the order given. After constructing a
PSO2
binary tree - a) Insert new node b) Find number of nodes in longest
path from root c) Minimum data value found in the tree d) Change a
tree so that the roles of the left and right pointers are swapped at every
node e) Search a value

PO1,
5 Construct an expression tree from the given prefix expression eg. +-- CO2 PO2,
a*bc/def and traverse it using postorder traversal(non recursive) and
PSO2
then delete the entire tree.

There are flight paths between cities. If there is a flight between city A CO2 PO1,
6 and city B then there is an edge between the cities. The cost of the edge PO2,
C can be the time that flight take to reach city B from A, or the amount of PSO2
fuel used for the journey. Represent this as a graph. The node can
be represented by airport name or name of the city. Use adjacency list
representation of the graph or use adjacency matrix representation of the

Department of Computer Engineering, MMCOE, Pune


Data Structures and Algorithms Lab Manual SE COMP, Sem-II

graph. Check whether the graph is connected or not. Justify the storage
representation used.

You have a business with several offices; you want to lease phone lines CO2 PO1,
7 to connect them up with each other; and the phone company charges PO2,
different amounts of money to connect different pairs of cities. You PSO2
want a set of lines that connects all your offices with a minimum total
cost. Solve the problem by suggesting appropriate data structures.

Given sequence k = k1 <k2 < ... <kn of n sorted keys, with a search CO3 PO1,
8 probability pi for each key ki . Build the Binary search tree that has PO2,
the least search cost given the access probability for each key? PO3
D
A Dictionary stores keywords & its meanings. Provide facility for CO3 PO1,
9 adding new keywords, deleting keywords, updating values of any PO2,
entry. Provide facility to display whole data sorted in ascending/ PSO2
Descending order. Also find how many maximum comparisons may
require for finding any keyword. Use Height balance tree and find the
complexity for finding a keyword

Read the marks obtained by students of second year in an online PO2,


10 examination of particular subject. Find out maximum and minimum CO PO4,
marks obtained in that subject. Use heap data structure. Analyze the 4 PSO2
E algorithm.

Department maintains a student information. The file contains roll PO2,


11 number, name, division and address. Allow user to add, delete CO PO4,
information of student. Display information of particular employee. If 4 PSO2
F record of student does not exist an appropriate message is displayed. If
it is, then the system displays the student details. Use sequential file to
maintain the data.

Company maintains employee information such as employee ID, name, CO PO2,


12 designation and salary. Allow users to add, delete information of 4 PO4,
employees. Display information of a particular employee. If an PSO2
employee does not exist an appropriate message is displayed. If it is,
then the system displays the employee details. Use index sequential file
to maintain the data.

PO1,
13 Content Design a mini project to implement a snake and ladder game using CO1 PO2,
Beyond Python. CO
PSO2
Syllabu 2
s

PO1,
14 V-Lab Study of DFS on binary trees CO2 PO2,
PSO2

Department of Computer Engineering, MMCOE, Pune


Software Required:

1. 64 bit open source operating system


2. Eclipse version 3.8.

Write-ups must include:

1. Group

2. Assignment No.

3. Title

4. Objective

5. Problem Statement

6. Outcomes

7. Theory(in brief)

8. Algorithm

9. Flowchart

10. Test Cases

11. Conclusion

12. FAQs

Department of Computer Engineering, MMCOE, Pune


GROUP: A
ASSIGNMENT NO: 1
Title: Implementation of a Hash Table.

Objective: To study the implementation of a hash Table.

Problem Statement: Consider a telephone book database of N clients. Make use of a hash table
implementation to quickly look up a client's telephone number. Make use of two collision handling
techniques and compare them using number of comparisons required to find a set of telephone numbers
(Python)

Outcome: Explain the concepts of Hashing and apply it to solve searching problems

Theory:
In a mathematical sense, a map is a relation between two sets. We can define Map M as a set of pairs,
where each pair is of the form (key, value), where for given a key, we can find a value using some kind
of a “function” that maps keys to values. The key for a given object can be calculated using a function
called a hash function. In its simplest form, we can think of an array as a Map where key is the index
and value is the value at that index. For example, given an array A, if i is the key, then we can find the
value by simply looking up A[i]. The idea of a hash table is more generalized and can be described as
follows. The concept of a hash table is a generalized idea of an array where a key does not have to be
an integer. We can have a name as a key, or for that matter any object as the key. The trick is to find a
hash function to compute an index so that an object can be stored at a specific location in a table such
that it can easily be found. Example: Suppose we have a set of strings {“abc”, “def”, “ghi”} that we’d
like to store in a table. Our objective here is to find or update them quickly from a table, actually in
O(1). We are not concerned about ordering them or maintaining any order at all. Let us think of a
simple schema to do this. Suppose we assign “a” = 1, “b”=2, … etc to all alphabetical characters. We
can then simply compute a number for each of the strings by using the sum of the characters as follows.
“abc” = 1 + 2 + 3=6, “def” = 4 + 5 + 6=15 , “ghi” = 7 + 8 + 9=24 If we assume that we have a table of
size 5 to store these strings, we can compute the location of the string by taking the sum mod 5. So we
will then store “abc” in 6 mod 5 = 1, “def” in 15 mod 5 = 0, and “ghi” in 24 mod 5
= 4 in locations 1, 0 and 4 as follows-
0 1 2 3 4
Def Abc ghi

Now the idea is that if we are given a string, we can immediately compute the location using a simple
hash function, which is the sum of the characters mod Table size. Using this hash value, we

Department of Computer Engineering, MMCOE, Pune


can search for the string. This seems to be a great way to store a Dictionary. Therefore the idea of
hashing seems to be a great way to store pairs of (key, value) in a table.

Implementation of a Simple Hash Table:


A hash table is stored in an array that can be used to store data of any type. In this case, we will define
a generic table that can store nodes of any type. That is, an array of void*’s can be defined as follows-

void* A[n];
The array needs to be initialized using for
(i = 0; i < n ; i++)
A[i] = NULL;
Suppose we like to store strings in this table and be able to find them quickly. In order to find out where
to store the strings, we need to find a value using a hash function. One possible hash function is
Given a string S = S1S2…. Sn
Define a hash function as
H(S) = H(“S1S2…. Sn”) = S1 + p S2 + p2 S3 + ….+ pn-1 Sn (1)
where each character is multiplied by a power of p, a prime number.
The above equation can be factored to make the computation more effective. Using the factored form,
we can define a function hash code that computes the hash value for a string s as follows— int
hashcode(char* s){
int sum = s[strlen(s)-1], p = 101; int
i;
for (i=1;i< strlen(s);i++) sum-
s[strlen(s)-i-1]+p*sum; return
sum;
}
This allows any string to be placed in the table as follows. We assume a table of size 101. A[hashcode(s)%101] =
s; // we assume that memory for s is already being allocated.
One problem with the above method is that if any collisions occur, that is two strings with the same
hash code,& we will lose one of the strings. Therefore we need to find a way to handle collisions in
the table.

Collisions:
One problem with hashing is that it is possible that two strings can hash into the same location. This is
called a collision. We can deal with collisions using many strategies, such as linear probing (looking
for the next available location i+1, i+2, etc. from the hashed value i), quadratic probing (same as linear
probing, except we look for available positions i+1 , i + 4, i + 9, etc from

Department of Computer Engineering, MMCOE, Pune


the hashed value i and separate chaining, the process of creating a linked list of values if they
hashed into the same location.
Algorithm:
1: Create a hash table with maximum size.
2: Define Hash function.
3: Read the telephone no & user’s information to insert it into the hash table.
4: Insert telephone no value in the hash table.
5: If collision occurs, apply a separate chaining.
6: If a user requires inserting another data, go to step 4.
7: Display all the user’s data.
8: Read the telephone no from the user to be found.
9: find the data from the hash table.
10: Display the data with minimum no. of comparisons.
Flowchart:

Department of Computer Engineering, MMCOE, Pune


Test Cases:

Sr. No Test ID Steps Input Expected Actual Result Status (Pass/


Result Fail)

1 ID01 Insert telephone no Telephone no & Data to be If key not FAIL


in the hash table the reference of inserted in the found,
hash table hash table segmentation
fault

2 ID02 Insert telephone no Telephone no & Data to be Data is PASS


in the hash table the reference of inserted in the inserted
hash table hash table

3 ID03 Find the Telephone no & Data found If not FAIL


telephone no in the reference of present, not
the hash table hash table found

4 ID04 Find the Telephone no & Data found If present, PASS


telephone no in the reference of not found
the hash table hash table

Conclusion:
Hence we have studied successfully the use of a hash table & implementing it.

Q 1. A hash table of length 10 uses open addressing with hash function h(k)=k mod 10, and linear
probing. After inserting 6 values into an empty hash. Draw hash table.

Q. 2 Which one of the following choices gives a possible order in which the key values could
have been inserted in the table?
(A) 46, 42, 34, 52, 23, 33
(B) 34, 42, 23, 52, 33, 46
(C) 46, 34, 42, 23, 52, 33
(D) 42, 46, 33, 23, 34, 52
.

Q 3. How many different insertion sequences of the key values using the same hash function
and linear probing will result in the hash table shown above?
(A) 10
(B) 20
(C) 30
(D) 40

Department of Computer Engineering, MMCOE, Pune


Q 4. The keys 12, 18, 13, 2, 3, 23, 5 and 15 are inserted into an initially empty hash table of length
10 using open addressing with hash function h(k) = k mod 10 and linear probing. What is the
resultant hash table?

(A) A
(B) B
(C) C
(D) D

Q 5. What terminates a failed linear probe in a full hash table?


(A) The end of the array
(B) A deleted node
(C) A null entry
(D) A node with a non-matching key
(E) Revisiting the original hash index

Q 6. If a hash table's array is resized to reduce collisions, what must be done to the elements that
have already been inserted?

Q 7. You need to store a large amount of data, but you don't know the exact number of elements.
The elements must be searched quickly by some key. You want to waste no storage space. The
elements to be added are in sorted order. What is the simplest data structure that meets your
needs?

Q 8. Is the hash table ADT?

Q 9. In a hash table that uses separate chaining to handle collisions, what, if any, restrictions
should be placed on the table size?

Q 10. Hashing is the best search method (constant running time) if we don't need to have the
records sorted. In that case which method will you use separate chaining or open addressing?

Q 11. What is Collision?

Department of Computer Engineering, MMCOE, Pune


ASSIGNMENT NO: 02

Title: Perform different operations and techniques on Hash table

Objective: To understand the collision resolution techniques and various operations on hash table

Problem Statement: Implement all the functions of a dictionary (ADT) using hashing and handle
collisions using chaining with / without replacement. Data: Set of (key, value) pairs, Keys are mapped to
values, Keys must be comparable, Keys must be unique Standard Operations: Insert(key, value), Find(key),
Delete(key) (python)

Outcome: Define class for Dictionary using Object Oriented features. Analyze working of hash function.

Theory:
Dictionary ADT Dictionary (map, association list) is a data structure, which is generally an association of
unique keys with some values. One may bind a value to a key, delete a key (and naturally an associated value)
and lookup for a value by the key. Values are not required to be unique. Simple usage example is an
explanatory dictionary. In the example, words are keys and explanations are values.
Dictionary Operations:

Dictionary create() creates empty dictionary
● boolean isEmpty(Dictionary d) tells whether the dictionary d is empty
● put(Dictionary d, Key k, Value v) associates key k with a value v; if key k already presents in
the dictionary old value is replaced by v

Value get(Dictionary d, Key k) returns a value, associated with key kor null, if dictionary contains
no such key
● remove(Dictionary d, Key k) removes key k and associated value
● destroy(Dictionary d) destroys dictionary d Hash Table is a data structure which stores data in
an associative manner.

In a hash table, data is stored in an array format, where each data value has its own unique index value. Access
of data becomes very fast if we know the index of the desired data. Thus, it becomes a data structure in which
insertion and search operations are very fast irrespective of the size of the data. Hash Table uses an array as a
storage medium and uses hash technique to generate an index where an element is to be inserted or is to be
located from.

Hashing: Hashing is a technique to convert a range of key values into a range of indexes of an array. We're
going to use the modulo operator to get a range of key values. Consider an example of a hash table of size 20,
and the following items are to be stored. Items are in the (key,value) format.

Basic Operations of hash table Following are the basic primary operations of a hash table.
● Search − Searches an element in a hash table.
● Insert − inserts an element in a hash table.
● Delete − Deletes an element from a hash table.

1. Data Item Define a data item having some data and key, based on which the search is to be conducted
in a hash table.
struct DataItem { int data; int key;
};

Department of Computer Engineering, MMCOE, Pune


Hash Method Define a hashing method to compute the hash code of the key of the data item. int
hashCode(int key)
{
return key % SIZE;
}

2. Search Operation Whenever an element is to be searched, compute the hash code of the key passed
and locate the element using that hash code as index in the array. Use linear probing to get the element ahead
if the element is not found at the computed hash code.
Example
struct DataItem *search(int key)
{
//get the hash int hashIndex = hashCode(key); //move in array until an empty while(hashArray[hashIndex]
!= NULL)
{
if(hashArray[hashIndex]->key == key)
return hashArray[hashIndex];
//go to next cell ++hashIndex;
//wrap around the table hashIndex %= SIZE;
}
return NULL; }

3. Insert Operation : Whenever an element is to be inserted, compute the hash code of the key passed
and locate the index using that hashcode as an index in the array. Use linear probing for empty location, if
an element is found at the computed hash code.
Example void insert(int key,int data)
{ struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem));
item->data = data;
item->key = key;
//get the hash int hashIndex = hashCode(key);
//move in array until an empty or deleted cell
while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1)
{ //go to next cell ++hashIndex; //wrap around the table hashIndex %= SIZE; }
hashArray[hashIndex] = item; }

4.. Delete Operation: Whenever an element is to be deleted, compute the hash code of the key passed and
locate the index using that hashcode as an index in the array. Use linear probing to get the element ahead if
an element is not found at the computed hash code. When found, store a dummy item there to keep the
performance of the hash table intact.
Example struct DataItem* delete(struct DataItem* item)
{ int key = item->key;
//get the hash int hashIndex = hashCode(key);
//move in array until an empty
while(hashArray[hashIndex] !=NULL)
{ if(hashArray[hashIndex]->key == key)
{ struct DataItem* temp = hashArray[hashIndex];
//assign a dummy item at deleted position hashArray[hashIndex] = dummyItem;

Department of Computer Engineering, MMCOE, Pune


return temp; }
//go to next cell ++hashIndex;
//wrap around the table hashIndex %= SIZE; } return NULL; }

Input: No. of. elements with key and value pair.


Output: Create a dictionary using a hash table and search the elements in the
table.

Flowchart:
Test Cases:

Sr. No Test ID Steps Input Expected Actual Result Status (Pass/


Result Fail)

1 01 Insert (4, Asmita) Read (4, Asmita) The (4, Asmita) If bucket is Pass
is inserted in it’s free and (4,
home bucket Asmita) is
inserted

2 02 Insert (4, Asmita) Read (4, Asmita) The record If fail


inserted in the calculate
hash table d
incorrect
bucket

Conclusion:
This program gives us the knowledge of dictionaries (ADT).

OUTCOME: Upon completion Students will be able to:


Learn object-oriented Programming features.
Understand & implement Dictionary (ADT) using hashing.

FAQ:

Q.1 How do you solve a collision hash?

Q.2 What is hashing and collision?

Q.3 What is hashing in data structure with an example?

Q.4 What happens in the hashing method to overcome collision?

Q.5 What is a hash index?

Q.6 What do you mean by hash table?

Q.7 Define Hashing.

Q.8 What do you mean by separate chaining?

Q.9 What do you mean by open addressing?

Q.10 Write the importance of hashing.


ASSIGNMENT NO: 03
Title:
Printing the tree level wise.

Objectives:
1. To understand concept of tree data structure
2. To understand concepts & features of object-oriented programming
3. To understand concept of class
4. To understand concepts & features of object-oriented programming.
5. To understand concept of tree data structure

Problem Statement:
A book consists of chapters, chapters consist of sections and sections consist of subsections. Construct
a tree and print the nodes. Find the time and space requirements of your method.

Outcome:
 Define class for structures using Object Oriented features.
 Analyze tree data structure.

Theory:

Introduction to Tree:
Definition:
A tree T is a set of nodes storing elements such that the nodes have a parent-child relationship that satisfies
the following
• If T is not empty, T has a special tree called the root that has no parent
• Each node v of T different than the root has a unique parent node w; each node with parent w is a
child of a tree.

A node that has no child is called a leaf, and that node is of course at the bottommost level of the tree. The
height of a node is the length of the longest path to a leaf from that node. The height of the root is the height
of the tree. In other words, the "height" of a tree is the "number of levels" in the tree. Or more formally, the
height of a tree is defined as follows:
1. The height of a tree with no elements is 0
2. The height of a tree with 1 element is 1
3. The height of a tree with > 1 element is equal to 1 + the height of its tallest subtree.

The depth of a node is the length of the path to its root (i.e., its root path). Every child node is always one
level lower than his parent. The topmost node in a tree is called the root node. Being the topmost node, the
root node will not have parents. It is the node at which operations on the tree commonly begin (although some
algorithms begin with the leaf nodes and work up ending at the root). All other nodes can be reached from it
by following edges or links. (In the formal definition, a path from a root to a node, for each different node is
always unique). In diagrams, it is typically drawn at the top.
Every node in a tree can be seen as the root node of the subtree rooted at that node.
Fig1. An example of a tree

Important Terms
Following are the important terms with respect to trees.
 Path − Path refers to the sequence of nodes along the edges of a tree.
 Root − The node at the top of the tree is called root. There is only one root per tree and one path from
the root node to any node.
 Parent − Any node except the root node has one edge upward to a node called parent. ∙
 Child − The node below a given node connected by its edge downward is called its child node.
 Leaf − The node which does not have any child node is called the leaf node.
 Subtree − Subtree represents the descendants of a node.
 Visiting − Visiting refers to checking the value of a node when control is on the node.
 Traversing − Traversing means passing through nodes in a specific order.
 Levels − Level of a node represents the generation of a node. If the root node is at level 0,
then its next child node is at level 1, its grandchild is at level 2, and so on.
 keys − Key represents a value of a node based on which a search operation is to be carried out
for a node.

Advantages of Trees
 Trees are so useful and frequently used, because they have some very serious advantages:
 Trees reflect structural relationships in the data
 Trees are used to represent hierarchies
 Trees provide an efficient insertion and searching
 Trees are very flexible data, allowing to move subtrees around with minimum effort for this
assignment we are considering the tree as follows.
Input: Book name & its number of sections and subsections along with name.

Output: Formation of tree structure for book and its sections.

Flowchart:
Test-cases:

Sr. Test Steps Input Expected Actual Result Status


No. ID Result (Pass/
Fail)

1 ID1 Enter count of Number of Nodes for Book node and Pass
chapters chapters is chapters are its children
nonzero positive created in the chapters are
value tree and created
attached as the
children of
book node
2 ID2 Enter count of Number of Nodes for chapter node Pass
sections sections is sections are and its children
nonzero positive created in the sections are
value tree and created
attached as the
children of
chapter node
3 ID3 Enter count of sub- Number of Nodes for sub- Section node Pass
sections subsections is sections are and its children
nonzero positive created in the sub-section
value tree and nodes are
attached as the created
children of
section node
4 ID1 Enter number Number of No subsection Number of Pass
of subsections: 0 node should be subsections is
subsections created zero hence no
as 0 children node
are introduced
for section node

Conclusion: This program gives us the knowledge tree data structure.

OUTCOME:
Upon completion Students will be able to:
Learn object-oriented Programming features.
Understand & implement tree data structure.

FAQs:

1. What is class, object and data structure?

2. What is tree data structure?

3. Explain different types of tree?


4. What is the difference between tree and Graph?

5. How do you check if a given binary tree is a subtree of another binary tree?

6. How do you find the distance between two nodes in a binary tree?

7. What is the Red-Black tree data structure?

8. What is Binary Tree and its application?

9. How are trees stored in memory?


GROUP: B
ASSIGNMENT NO: 04

Title: Different operations on binary trees.

Objective: To study Different operations on binary trees.

Problem Statement: Beginning with an empty binary search tree, construct a binary search tree by
inserting the values in the order given. After constructing a binary tree -
1. Insert new node
2. Find number of nodes in longest path from root
3. Minimum data value found in the tree
4. Change a tree so that the roles of the left and right pointers are swapped at every node
5. Search a value

Outcome: Classify the Tree data structures & apply it for problem solving

Theory:
A binary tree is composed of nodes connected by edges. Some binary tree is either empty or consists of a
single root element with two distinct binary tree child elements known as the left subtree and the right
subtree of a node. As the name binary suggests, a node in a binary tree has a maximum of children.
An important special kind of binary tree is the binary search tree (BST). In a BST, each node stores some
information including a unique key value, and perhaps some associated data. A binary tree is a BST iff, for
every node n in the tree:

 All keys in n's left subtree are less than the key in n, and
 all keys in n's right subtree are greater than the key in n.

Algorithm:
Algorithm to insert a node in the binary tree:
1. Create a new BST node and assign values to it.
2. insert(node, key)
i) If root == NULL,
return the new node to the calling function.
ii) if root=>data < key
call the insert function with root=>right and assign the return value in root=>right.
root->right = insert(root=>right,key)
iii) if root=>data > key
3. call the insert function with root->left and assign the return value in root=>left.
4. root=>left = insert(root=>left,key)
5. Finally, return the original root pointer to the calling function.

Algorithm to find the minimum value in binary tree:


1. Define Node class which has three attributes namely: data, left and right. Here, left represents the left
child of the node and right represents the right child of the node.
2. When a node is created, data will pass to the data attribute of node and both left and right will be set to
null.
3. Define another class which has an attribute root.
A) Root represents the root node of the tree and initializes it to null.
Flow-Chart:
Test Cases:

Sr. Test ID Steps Input Expected Result Actual Result Status


No (Pass/Fail)

1 01 Inserting a Read value Value inserted either Segmentation Fail


node in binary from user in left subtree or fault
search tree right subtree

2 02 Finding a value Read value According to the If inserted exactly fail


in the tree from user property of BST , it reverse of the
should display the property
result
3 03 Finding a value Read value According to the If inserted exactly Pass
in the tree from user property of BST , it according to the
should display the property of BST
result

Conclusion:
Hence we have studied successfully how to delete any node from a binary tree using operator
overloading.

FAQs:
Q 1. List any four Operators that cannot be overloaded?

Q 2. What is a Copy Constructor?

Q 3. Give an example for a Copy Constructor.

Q 4. What is the need for Overloading an operator?

Q 5. What are the applications of binary trees?

Q 6. List out the cases involved in deleting a node from a binary search tree.

Q 7. A + (B-C)*D+(E*F), if the above arithmetic expression is represented using a binary tree,


Find the number of non-leaf nodes in the tree.

Q 8. Give various implementations of trees.

Q 9. Define binary search tree. Why is it preferred rather than the sorted linear array and linked
list?

Q 10. Define a complete binary tree.


ASSIGNMENT NO: 5

Title: Study of Expression tree.

Objective: Understand construction of expression tree from given prefix expression.


Understand Non Recursive post order traversal.

Problem Statement: Construct an expression tree from the given prefix expression eg. +--a*bc/def
and traverse it using post order traversal (non-recursive) and then delete the entire tree.

Outcome: Postorder expression for given prefix expression

Theory:
The expression tree is a binary tree in which each internal node corresponds to the operator and each
leaf node corresponds to the operand so for example expression tree for 3 + ((5+9)*2) would be:

There are different types of expression formats:


Prefix expression
Infix expression and
Postfix expression

Expression Tree is a special kind of binary tree with the following properties:
1. Each leaf is an operand. Examples: a, b, c, 6, 100
2. The root and internal nodes are operators. Examples: +, -, *, /, ^
3. Subtrees are subexpressions with the root being an operator.

Traversal Techniques:

There are 3 standard traversal techniques to represent the 3 different expression formats.

Inorder Traversal:
We can produce an infix expression by recursively printing out
the left expression,
the root, and
the right expression.

Postorder Traversal:
The postfix expression can be evaluated by recursively printing out
the left expression,
the right expression and
then the root

Preorder Traversal:
1) We can also evaluate prefix expression by recursively printing out:
2) the root,
3) the left expressoion and
4) the right expression.

Algorithm:
Construction of Expression Tree:

1. Read the Prefix expression in reverse order (from right to left)


2. If the symbol is an operand, create one node tree and then push it onto the Stack
3. If the symbol is an operator, then pop two pointers from the Stack namely T1 &T2 and form a
new tree with root as operator T1 & T2 as a left and right child. A pointer to this new tree is pushed onto
the stack
4. Repeat the above steps until end of Prefix expression.

Post order Traversal –Non recursive:

Using two Stack S1 & S2


1. Push root to first stack.
2. Loop while first stack is not empty
2.1 Pop a node from first stack and push it to second stack
2.2 Push left and right children of the popped node to first stack
3. Print contents of second stack
Flowchart:

● Construction of Expression Tree:


● Post order Traversal –Non recursive:

Test Cases:

Sr. No. Test ID Steps Input Expected Actual Status


Result Result (Pass/F
ail)
1 ID1 Given an prefix Prefix Respective Tree Pass
expression the tree is expression tree constructed
constructed for the
expression
2 ID2 Give Incomplete prefix Incomplete Display Display Pass
expression prefix error error
expression message on message on
screen screen
3 ID3 Postorder traversal of Expression Postorder Postorder Pass
the expression tree tree traversal traversal
sequence of sequence of
the the
expression expression
tree tree
FAQs:
Q1. What is expression tree?

Q2. At which position operators present in Expression tree?

Q3. At which position operands present in Expression tree?

Q4. What is output for inorder traversal on Expression Tree?

Q5. What are infix , postfix and prefix expression?

Q6. What is use of stack in program?

Q7. Can STL used instead of user defined stack in program?

Q8. What are applications of trees?

Q9. What are applications for stack?

Q10. What is difference between tree and graph?


GROUP: C
ASSIGNMENT NO: 6
Title: Study types of representation of the Graph

Objective: To implement Adjacency Matrix representation of graph

Problem Statement: There are flight paths between cities. If there is a flight between city A and city
B then there is an edge between the cities. The cost of the edge can be the time that flight takes to reach
city B from A or the amount of fuel used for the journey. Represent this as a graph. The node can be
represented by airport name or name of the city. Use adjacency list representation of the graph or use
adjacency matrix representation of the graph. Justify the storage representation used.

Outcome:
Summarize the basic concepts and operations on Graph data structure & apply it for solving real life
problems

Theory:
Graph is a data structure that consists of following two components:
1. A finite set of vertices also called as nodes.
2. A finite set of ordered pair of the form (u, v) called as edge.
The pair is ordered because (u, v) is not same as (v, u) in case of directed graph(di-graph). The pair of
form (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain
weight/value/cost.
Following is an example undirected graph with 5 vertices.

Following two are the most commonly used representations of graph.


1. Adjacency Matrix
2. Adjacency List
There are other representations also like, Incidence Matrix and Incidence List. The choice of the
graph representation is situation specific. It totally depends on the type of operations to be performed
and ease of use.
Adjacency Matrix:
Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D
array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. Adjacency
matrix for undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted
graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w.
The adjacency matrix for the above example graph is:

Adjacency Matrix Representation of the above graph


Pros: Representation is easier to implement and follow. Removing an edge takes O(1) time. Queries
like whether there is an edge from vertex ‘u’ to vertex ‘v’ are efficient and can be done O(1).
Cons: Consumes more space O(V^2). Even if the graph is sparse(contains less number of edges), it
consumes the same space. Adding a vertex is O(V^2) time.

Adjacency List:
An array of linked lists is used. Size of the array is equal to number of vertices. Let the array be array[
]. An entry array[i] represents the linked list of vertices adjacent to the i th vertex. This representation
can also be used to represent a weighted graph. The weights of edges can be stored in nodes of linked
lists. Following is adjacency list representation of the above graph.
Adjacency List Representation of the above Graph
Applications:
Graphs are used to represent many real life applications: Graphs are used to represent networks. The
networks may include paths in a city or telephone network or circuit network. Graphs are also used in
social networks like linkedIn, facebook. For example, in facebook, each person is represented with a
vertex(or node). Each node is a structure and contains information like person id, name, gender and
locale.
Algorithm:
Graph creation using Adjacency Matrix

 Declare an array of M[size][size] which will store the graph.


 Enter how many nodes you want in a graph.
 Enter the edges of the graph by two vertices each, say Vi , Vj indicates some edge
 If the graph is directed set M[i][j]=1. If graph is undirected set M[i][j] =1 and M[j][i] =1 as
well.
 When all the edges of the desired graph is entered print the graph M[i][j].

Graph creation using Adjacency list

 Declare node structure for creating adjacency list.


 Initialize an array of nodes. This array will act as head nodes. The index of head[ ] will be
the starting vertex.
 The create function will create the adjacency list.
Flow Chart:

Test cases:

Sr. Test Steps Input Expected Actual Result Status


No. ID Result (Pass/
Fail)

1 ID1 Enter the All 0’s Graph is not If for any vertex there Fail
matrix values connected shows a adjacent
vertex
2 ID2 Enter the All 0’s Graph is not No Adjacent vertex Pass
matrix values connected shown

3 ID3 Enter the Some non zero Some No adjacent vertex Fail
matrix values values edges are present
and remaining present
zero’s
4 ID4 Print the {0,1,1,0,1,0,0,1, 1,2,4,3 1,2,4,3 or Pass
graph using DFS 1,0,0,1,0,1,1,0} 1,3,4,2
5 ID5 Print the {0,1,1,0,1,0,0,1, 1,2,4,3 1,3,2,4 Fail
graph using DFS 1,0,0,1,0,1,1,0}

Conclusion: Graph representation using adjacency matrix is implemented successfully.


FAQs :

Q1. What are the advantages of adjacency list representation over adjacency matrix
representation of a graph?

Q2. Define graph

Q3. What is adjacency matrix?

Q4. What is adjacency list?

Q5. For an undirected graph with n vertices and e edges, the sum of the degree of each
vertex is equal to

Q6. The maximum degree of any vertex in a simple graph with n vertices is

Q7. What are the advantages and disadvantages of Adjacency matrix

Q8. What are the advantages and disadvantages of Adjacency list

Q9. Which algorithm can be used to most efficiently determine the presence of a cycle in a given
graph ?

Q10. Given two vertices in a graph s and t, which of the two traversals (BFS and DFS) can be
used to find if there is path from s to t?
ASSIGNMENT NO: 7

Title : Study of minimum spanning tree

Objective : To implement Minimum Spanning Tree

Problem Statement : You have a business with several offices; you want to lease phone lines to
connect them up with each other; and the phone company charges different amounts of money to
connect different pairs of cities. You want a set of lines that connects all your offices with a minimum
total cost. Solve the problem by suggesting appropriate data structures.

Outcomes : Explain the concepts of Hashing and apply it to solve searching problems

Theory :
Spanning Trees: A sub-graph T of a undirected graph G=(V,E) is a spanning tree of G if it is a tree and
contains every vertex of G. Minimum Spanning Tree in an undirected connected weighted graph is a
spanning tree of minimum weight (among all spanning trees).
Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a
connected weighted undirected graph. This means it finds a subset of the edges that forms a tree
that includes every vertex, where the total weight of all the edges in the tree is minimized. Start form
any arbitrary vertex Find the edge that has minimum weight form all known vertices Stop when the
tree covers all vertices
Algortithm:
Prim’s Algorithm:
MST= {0} // start with vertex 0
For (T=0; T contains fewer than n-1 edges; add(u,v) to T)
{
Let (u,v) be a least cost edge such that u є TV & v not belonging to TV; Add V
to TV
}
Flow Chart :

Test Cases:

Sr. Test ID Steps Input Expecte Actual Result Status (Pass/


No. d Fail)
Result
1 ID1 Take no. of vertices Enter two An An Pass
and edges. for e.g. 5 vertices and the adjacen adjac
and 8 cost of cy matrix ency matrix
edge representation representation
between them of graph of graph
2 ID2 Vertices with no Cost[i][j]=infin Cost between Some are not Fail
edge between them ity all the vertices made
are assigned some having no edge
value infinity between them
should be
made infinity

3 ID3 Enter the cost of 1 2 10 13542 13542 Pass


edges present 135
148
243
257
344
352
451
4 ID4 Enter the cost of 1 2 10 13542 13425 Fail
edges present 135
148
243
257
344
352
451
5 ID5 While finding the if all vertices Visited If Visited[5]=0 Fail
MST are not visited [1 to 5]=1

Conclusion: Minimum Spanning Tree assignment has implemented successfully.

FAQs:
Q 1.What is MST?

Q 2. Which algorithms are available for finding MST for given graph?

Q 3.Which algorithm you have used in program?

Q 4. What is constructor, types of constructor

Q 5. Have you used constructor is assignment? If Yes, what is its type?

Q 6. Why visited array is used in program?

Q 7. How many edges does a minimum spanning tree has?


Q 8. How does Prim’s Algorithm Work?

Q 9. Does the minimum spanning tree of a graph give the shortest distance between any 2
specified nodes?

Q 10. What is a spanning Tree?


Group: D
Assignment No.: 08

Title: Study to create least cost binary tree

Objectives:
1. To understand concept of OBST.
2. To understand concept & features like extended binary search tree.
3. To understand concept of OBST.
4. To understand concept & features like extended binary search tree.

Problem Statement:
Given sequence k = k1 <k2 < ... <kn of n sorted keys, with a search probability pi for each key ki.
Build the Binary search tree that has the least search cost given the access probability for each key?

Outcome:
 Define class for Extended binary search tree using Object Oriented features.
 Analyze working of functions.

Theory:
An optimal binary search tree is a binary search tree for which the nodes are arranged on levels such that
the tree cost is minimum.
For the purpose of a better presentation of optimal binary search trees, we will consider “extended binary
search trees”, which have the keys stored at their internal nodes. Suppose “n” keys k1, k2, … k n are stored
at the internal nodes of a binary search tree. It is assumed that the keys are given in sorted order, so that k1<
k2 < … < kn.
An extended binary search tree is obtained from the binary search tree by adding successor nodes to each
of its terminal nodes as indicated in the following figure by squares:
In the extended tree:
 The squares represent terminal nodes. These terminal nodes represent unsuccessful searches
of the tree for key values. The searches did not end successfully, that is, because they
represent key values that are not actually stored in the tree;
 The round nodes represent internal nodes; these are the actual keys stored in the tree.
 Assuming that the relative frequency with which each key value is accessed is known,
weights can be assigned to each node of the extended tree (p1 … p6). They represent
the relative frequencies of searches terminating at each node, that is, they mark the successful
searches.
 If the user searches a particular key in the tree, 2 cases can occur:
1 – the key is found, so the corresponding weight „p‟ is incremented;
2 – the key is not found, so the corresponding „q‟ value is incremented.

GENERALIZATION:
The terminal node in the extended tree that is the left successor of k1 can be interpreted as representing
all key values that are not stored and are less than k1. Similarly, the terminal node in the extended tree
that is the right successor of kn, represents all key values not stored in the tree that are greater than kn.
The terminal node that is successes between ki and ki-1 in an inorder traversal represent all key values
not stored that lie between ki and ki - 1.

ALGORITHMS
We have the following procedure for determining R(i, j) and C(i, j) with 0 <= i <= j <= n: PROCEDURE
COMPUTE_ROOT(n, p, q; R, C)
begin
for i = 0 to n do
C (i, i) ←0
W (i, i) ←q(i) for
m = 0 to n do
for i = 0 to (n – m) do j
←i + m
W (i, j) ←W (i, j – 1) + p (j) + q (j)
*find C (i, j) and R (i, j) which minimize the
tree cost
end
The following function builds an optimal binary sea rch
tree
FUNCTION CONSTRUCT(R, i, j)
begin
*build a new internal node N labeled (i, j) k ←R (i, j)
f i = k then
*build a new leaf node N‟ labeled (i, i)
else
*N‟ ←CONSTRUCT(R, i, k)
*N‟ is the left child of node N
if k = (j – 1) then
*build a new leaf node N‟‟ labeled (j, j)
else
*N‟‟ ←CONSTRUCT(R, k + 1, j)
*N‟‟ is the right child of node N
return N end

COMPLEXITY ANALYSIS:
The algorithm requires O (n2) time and O (n2) storage. Therefore, as „n‟ increases it will run out of
storage even before it runs out of time. The storage needed can be reduced by almost half by
implementing the two-dimensional arrays as one-dimensional arrays.

Input:
 No. of Element
 key values
 Key Probability

Output: Create binary search tree having optimal searching cost.

Conclusion: This program gives us the knowledge OBST, Extended binary search tree.
OUTCOME: Upon completion Students will be able to:
 Learn object oriented Programming features.
 Understand & implement extended binary search tree.

FAQS:
Q 1.What is BST?

Q 2. What is difference in Binary tree and BST?

Q 3. What is friend class?

Q4. What is constructor , types of constructor

Q5. Have you used constructor is assignment?

Q6. Which value is returned by strcmp( ) function

Q7. What is use of strcpy function()?

Q8. What are traversals done on tree to display data?

Q9. Inorder traversal will display the data of dictionary in which order/sequence?

Q10. Out of two classes in program , which class object is created and which class pointer is
created?
ASSIGNMENT NO: 9

Title: Study of AVL trees

Objective: To implement AVL Trees

Problem Statement: A Dictionary stores keywords & its meanings. Provide facility for adding new
keywords, deleting keywords, updating values of any entry. Provide facility to display whole data
sorted in ascending/ Descending order. Also find how many maximum comparisons may require for
finding any keyword. Use Height balance tree and find the complexity for finding a keyword.

Outcome: Describe the concept of symbol tables with OBST and AVL trees

Theory:
An AVL tree (Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary
search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one;
Balance factor = heightOfLeftSubtree – heightOfRightSubtree

if at any time they differ by more than one, rebalancing is done to restore this property. Lookup,
insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number
of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced
by one or more tree rotations.
Example AVL tree
AVL Tree Rotations:
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.

Single Left Rotation (LL Rotation)


In LL Rotation every node moves one position to left from the current position.
Single Right Rotation (RR Rotation)
In RR Rotation every node moves one position to right from the current position.

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.

Right Left Rotation (RL Rotation)


The RL Rotation is combination of single right rotation followed by single left rotation. In RL Rotation,
first every node moves one position to right then one position to left from the current position.
The following operations are performed on an AVL tree...
1. Search
2. Insertion
3. Deletion
Algorithm :
Insertion Operation in AVL Tree
In an AVL tree, the insertion operation is performed with O(log n) time complexity. In AVL Tree, new
node is always inserted as a leaf node. The insertion operation is performed as follows...

Step 1: Insert the new element into the tree using Binary Search Tree insertion logic.
Step 2: After insertion, check the Balance Factor of every node.
Step 3: If the Balance Factor of every node is 0 or 1 or -1 then go for next operation.
Step 4: If the Balance Factor of any node is other than 0 or 1 or -1 then tree is said to be
imbalanced. Then perform the suitable Rotation to make it balanced. And go for next operation.

Search Operation in AVL Tree


In an AVL tree, the search operation is performed with O(log n) time complexity. The search operation
is performed similar to Binary search tree search operation. We use the following steps to search an
element in AVL tree…
Step 1: Read the search element from the user
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.
Deletion Operation in AVL Tree
In an AVL Tree, the deletion operation is similar to deletion operation in BST. But after every deletion
operation we need to check with the Balance Factor condition. If the tree is balanced after deletion
then go for next operation otherwise perform the suitable rotation to make the tree Balanced.
Flowchart:
Test Cases:

Sr. Test Steps Input Expected Result Actual Result Statu s


NO ID (Pass/
Fail)

1 ID1 Enter the data and Happy Good Sorted list of data Cat Pet Animal Pass
display AVL tree Mood Zoo Wild to be displayed Happy Good Mood
Animals Cat Pet Zoo Wild Animals
Animal

2 ID2 Enter the data Happy Good Required data Message displayed Fail
and Mood Zoo Wild is present data is not present
search present Animals Cat Pet
data Animal

3 ID3 Enter the data and Happy Good Required data Message displayed Fail
search non Mood Zoo Wild is absent data is present
existing data Animals Cat Pet
Animal

4 ID4 Search in empty No Input AVL Tree is empty Message displayed Pass
AVL AVL Tree is empty

5 ID5 Enter the data , Happy Good Happy Good Mood Cat Pet Animal Fail
display AVL tree Mood Zoo Wild Zoo Wild Animals Happy Good Mood
and delete node Animals Cat Pet Zoo Wild Animals
Animal

Conclusion: Dictionary assignment has been implemented successfully using binary search trees.

FAQs:
Q 1. What is AVL tree?

Q 2. What does AVL stand for?

Q 3. Is AVL a BST?

Q.4 AVL is binary search tree. Q 4. What is balance factor in AVL?

Q 5. What are single rotations ?

Q 6. What are double rotations ?

Q 7. What is time complexity of using AVL tree?

Q 8. What is height of AVL tree?


Q 9. How to calculate Balance factor?

Q 10. What are applications of A VL Trees

Q 11. Compare AVL tree with Red-Black Tree.


GROUP:D
ASSIGNMENT NO:10

Title: Study Heap data structure

Objective: To understand Max heap and Min heap.

Problem Statement:Read the marks obtained by students of second year in an online examination of
particular subject. Find out maximum and minimum marks obtained in that subject. Use heap data
structure. Analyze the algorithm.

Outcome: Demonstrate and apply knowledge of Indexing and Multiway Trees

Theory:
Heap: Heap is a special case of balanced binary tree data structure where the root-node key is
compared with its children and arranged accordingly. If α has child node β then −
key(α) ≥ key(β)
As the value of parent is greater than that of child, this property generates Max Heap. Based on this
criteria, a heap can be of two types −

Min-Heap − Where the value of the root node is less than or equal to either of its children.

Max-Heap − Where the value of the root node is greater than or equal to either of its children.
Implementation
Algorithm :

1. Accept the marks for student.


2. Insert the marks in heap.
3. Up-adjust the heap.
4. Repeat the steps 1 to 4 if marks of more students to be entered.
5. Display the maximum marks.
Flowchart:
Test Cases:

Sr. Test Steps Input Expected Result Actual Result Statu s


NO ID (Pass/
Fail)

1 ID1 Construct a Max 10 20 30 Maximum marks to Maximum marks is Pass


heap and display be displayed 30 displayed as 30
maximum
marks.

2 ID2 Construct a Min 40 20 10 Minimum marks to Minimum marks is Pass


heap and display be displayed 10 displayed as 10
minimum marks.

3 ID3 Construct a Max 50 10 90 Maximum marks to Maximum marks is Fail


heap and display be displayed 90 displayed as 500
maximum
marks.

4 ID4 Construct a Min 70 10 30 Minimum marks to Minimum marks is Fail


heap and display be displayed 10 displayed as 30
minimum marks.

Conclusion: Max Heap and Min heap are implemented Successfully.


FAQs:
Q 1. What is Heap?

Q 2. How data is stored in Heap?

Q 3. What are operations on Heap?

Q 4. What is Max Heap?

Q 5. What is Min Heap?

Q 6. At Which position maximum data is present in Max heap?

Q 7. At Which position minimum data is present in Max heap?

Q 8. What are applications of Heap?


GROUP: F
ASSIGNMENT NO: 11
Title: Study of Sequential files

Objective: To Study Sequential file system.

Problem Statement: Department maintains a student information. The file contains roll number,
name, division and address. Allow user to add, delete information of student. Display information of
particular employee. If record of student does not exist an appropriate message is displayed. If it is,
then the system displays the student details. Use sequential file to maintain the data.

Outcomes:
To use effective and efficient data structures in solving various Computer Engineering domain problems.

Theory :
Many real life problems use large volume of data and in such cases we require to use some devices
such as floppy disk or hard disk to store the data. The data in these devices is stored using the concept
of files . A file is a collection of related data stored in a particular area on the disk. Programs can be
designed to perform the read and write operations on these files.
A program involves either or both of following types of data communication.
1. Data transfer between the console and the program
2. Data transfer between the program and a disk file.

The I/O system of C++ contains a set of classes that define the file handling methods.
These include ifstream, ofstream and fstream . These classes are derived from fstream base and
from corresponding stream classes. These classes are declared in fstream.h header file. We must
include this file in the program that uses file.

Details of file stream classes


Fstreambase: Serves as a base for fstream, ifstream and ofstream class. Contains close( ) and open( )
Ifstream : Provides input operations. Contains open( ) with default input mode. Inherits the
functions get(), getline( ), read( ), seekg( ) and tellg( ) functions from istream.
Ofstream: Provides output operations. Contains open( ) with default output mode. Inherits the
functions put( ), write( ),seekp( ) and tellp( ) functions from ostream.
Fstream: Provides support for i/p and o/p operations.Contains open( ) without default mode. Inherits
all the functions from istream and ostream classes through iostream.
Filebuf: To set file buffers to read and write

A file can be opened in two ways:

 Using the constructor function of the class: This method is useful when we use only one
file in the stream.

 Using the member function open( ) of the class. : This method is used when we want to
manage multiple files using one stream.
Opening Files Using Constructor
Filename is used to initialize the file stream object. There are 2 steps :

Create a file stream object to manage the stream using appropriate class Initialize the file object
with the desired filename.
Ex. Ofstream outfile(“result”);
Open : File Modes
The general form of the function open( ) with two arguments is :

stream-object.open(“filename”, mode);
The second argument mode specifies the purpose for which the file is opened. The prototype of the
class member functions contain default values for the second argument .

The default values are as :


ios :: in for ifstream functions open for reading only
ios:: out for ofstream functions open for writing only
The file mode parameter can take one (or more) of constants defined in the class ios().

Parameter Meaning
ios :: app Append to end-of –file.
ios::ate Go to end-of-file on opening.
ios::in Open file for reading only
ios::nocreate Open fails if file does not exist
ios::noreplace Open fails if file already exists
ios::out Open file for writing only
ios::trunc Delete the contents of the file if it exists
ios::binary Binary file

File Pointers and Their Manipulations


Each file has two associated pointers known as file pointers. One of them is called input pointer(or get
pointer) and the other is called the output pointer(or put pointer).

We can use these pointers to move through the files while reading or writing . The input pointer is used
for reading the contents of a given location and the output pointer is used for writing to a given location.

Each time an input or output operation takes place , the appropriate pointer is automatically adjusted

Default actions
When we open a file in read-only mode , the input pointer is automatically set at the beginning so that
we can read the file from the start.
When we open a file in write-only mode, the existing contents are deleted and the output pointer is set
at the beginning of the file. This enables to write to the file from the start

When we want to open an existing file to add more data , the file is opened in ‘append’ mode . This
moves the output pointer to the end of file.
The file stream classes support the functions to manage movements of the file pointers
seekg( ) Moves get pointer to a specified location.
seekp( ) Moves put pointer to a specified location.
tellg( ) Gives the current position of the get pointer.
tellp( ) Gives the current position of the put pointer.

Seek functions seekg( ) and seekp( ) can also be used with two arguments:

Seekg(offset, refposition);
Seekp(offset, refposition);

The parameter offset represents the number of bytes the file pointer is to be moved from the
location specified by the parameter refposition.

The refposition takes one of following three constants defined in the ios class:

ios::beg start of the file


ios::cur current position of the pointer
ios::end End of the file

The seekg() function moves associated file’s ‘get’ pointer while the seekp() function moves the
associated file’s ‘put’ pointer.

Sequential Input and Output Operations


The file stream classes support a number of member functions for performing the input and
output operations on files.

The first pair of functions , put( ) and get( ) are designed for handling a single character at a time
Second pair of functions, write( ) and read( ) are designed to write and read a blocks of binary data.

Put( ) and get( ) Functions


The function put( ) writes a single character to the associated stream The
function get( ) reads a single character from the associated stream

Write( ) and read( ) Functions


The functions write( ) and read( ) , unlike the functions put( ) and get( ) handle the data in binary form.
The binary format is more accurate for storing the numbers as they are stored in the exact internal
representation.
The binary input and output functions takes form as:

infile.read ((char *) &V, sizeof (V) );


outfile.write ((char *) &V, sizeof (V) );

The functions takes two arguments . The first is the address of the variable V and the second is the
length of variable in bytes.

Algorithm :

1. Open the file


2. Write the student record in file.
3. Display all contents of filename
4. Delete the required student record from file and d display the contents
5. Search for specific student record and display respective record.
Flowchart:
Test Cases:

Sr. Test Steps Input Expected Result Actual Result Statu s


No. ID (Pass/
Fail)

1 ID1 Open the file in 12 Amit Data to be written Data is written in Pass
ios::out mode I Kothrud in file file

2 ID2 Open the file in No input Data from file to be Data from file is Pass
ios::in mode displayed displayed

3 ID3 Open the file in Roll No 12 Respective student Different student Fail
ios::in mode, record to be record is played
search record displayed

4 ID4 Open the file in Roll No 10 All contents of file All contents of file Pass
ios::out mode, except except
delete record deleted deleted
and display record to record are
be displayed displayed
5 ID5 Open the file in 15 Rahul Newly added New record is Pass
ios::out I Karvenagar record to displayed as last
mode, be displayed at end record
append
record and
display

Conclusion: Sequential Files are implemented successfully for Student database system.

FAQs:
Q 1. What is file?

Q 2. What are Sequential Input and Output Operations?

Q 3. What are character input output functions?

Q 4. What are file pointers?

Q 5. What are file opening modes?

Q 6. What is syntax of read and write functions?

Q 7. What are functions for file pointers movement?

Q 8. In which header file , stream classes are declared?


Q 9. What is a stream :

Q10. What are stream classes?


Assignment No: 12

Title: Study of Use index sequential file

Objective: To understand the concept and basic of index sequential file and its use in Data structure

Problem Statement: Company maintains employee information as employee ID, name, designation and
salary. Allow user to add, delete information of employee. Display information of particular employee. If
employee does not exist an appropriate message is displayed. If it is, then the system displays the employee
details. Use index sequential file to maintain the data

Outcome:
To implement the concept and basic of index sequential file and to perform basic operation as adding record,
display all record, search record from index sequential file and its use in Data structure.

Theory :
 Indexed sequential access file organization
 Indexed sequential access file combines both sequential file and direct access file organization.
 In indexed sequential access file, records are stored randomly on a direct access device such as magnetic
disk by a primary key.
 This file have multiple keys. These keys can be alphanumeric in which the records are ordered is called
primary key.
 The data can be access either sequentially or randomly using the index. The index is stored in a file and
read into memory when the file is opened.

Primitive operations on Index Sequential files:


 Write (add, store): User provides a new key and record, IS file inserts the new record and key.
 Sequential Access (read next): IS file returns the next record (in key order)
 Random access (random read, fetch): User provides key, IS file returns the record or "not there"
 Rewrite (replace): User provides an existing key and a new record, IS file replaces existing record with
new.
 Delete: User provides an existing key, IS file deletes existing record

Algorithm:
Step 1 - Include the required header files (iostream.h, conio.h, and windows.h for colors).
Step 2 - Create a class (employee) with the following members as public members. emp_number,
emp_name, emp_salary, as data members. get_emp_details(), find_net_salary() and show_emp_details() as
member functions.
Step 3 - Implement all the member functions with their respective code (Here, we have used scope
resolution operator ::). Step 3 - Create a main() method.
Step 4 - Create an object (emp) of the above class inside the main() method.
Step 5 - Call the member functions get_emp_details() and show_emp_details().
Step 6 - return 0 to exit form the program execution.

Approach:
1. For storing the data of the employee, create a user define datatype which will store the information
regarding Employee. Below is the declaration of the data type:
2. struct employee
{
3. string name;
4. long int Employee_id;
5. string designation;
6. int salary;
7. };

Building the Employee's table:


For building the employee table the idea is to use the array of the above struct datatype which will use to
store the information regarding employee.
For storing information at index i the data is stored as:
struct employee emp[10];
emp[i].name = "GeeksforGeeks"
emp[i].code = "12345"
emp[i].designation = "Organisation"
emp[i].exp = 10 emp[i].age = 10

Deleting in the record: Since we are using array to store the data, therefore to delete the data at any index
shift all the data at that index by 1 and delete the last data of the array by decreasing the size of array by 1

Searching in the record: For searching in the record based on any parameter, the idea is to traverse the data
and if at any index the value parameters matches with the record stored, print all the information of that
employee.

Conclusion: Index Sequential Files are implemented successfully for Student database system.

FAQs:

Q 1. What are the advantages of indexed sequential file organization?

Q 2. What are the dis advantages of indexed sequential file organization?

Q 3. What are the objectives of file organization?

Q 4. What are the types of file organization?

Q 5. What are the advantages of direct access file organization?

Q.6. What are the disadvantages of direct access files?

Q.7. What are the advantages of sequential access file?

Q.8. What are the dis advantages of sequential access file?

Q.9. What are the important features of files?


Q.10. What is cluster file organization?

Q.11. What are the types of cluster file organization?

Q.12. What are the advantages of cluster file organization?


Assignment No: 13
Title: To apply BFS and queue combined

Objective: To understand the application of BFS.

Problem Statement: Design a mini project to implement snake and ladder game using Python.

Outcome: apply the graph traversals

Theory: The idea is to consider the snakes and ladders board as a directed graph and run Breadth–first search
(BFS) from the starting node, vertex 0, as per game rules. We construct a directed graph, keeping in mind the
following conditions:
1. For any vertex in graph v, we have an edge from v to v+1, v+2, v+3, v+4, v+5, v+6 as we can reach any
of these nodes in one throw of dice from node v.
2. If any of these neighbors of v has a ladder or snake, which takes us to position x, then x becomes the
neighbor instead of the base of the ladder or head of the snake.

Now the problem is reduced to finding the shortest path between two nodes in a directed graph problem. We
represent the snakes and ladders board using a map.

Output: Attach program and output of the project


Assignment No: 14
Title: Study DFS traversal on binary trees.

Objective: To understand DFS traversal on binary trees.

Problem Statement: Implementation of DFS traversal on binary trees using Python classes.

Outcome: Classify the Tree data structures & apply it for problem solving

Theory:
Binary Tree: A binary tree is a tree data structure in which each node has at most two children, which
are referred to as the left child and the right child.
Example of binary tree

Tree Traversals (Inorder, Preorder and Postorder)

Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way
to traverse them, trees can be traversed in different ways. Following are the generally used ways for
traversing trees.

Inorder Traversal:
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)

Preorder Traversal:

Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)

Postorder Traversal:

Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.

Example of Traversal

Depth First Traversals:


a. Inorder (Left, Root, Right) : 4 2 5 1 3
b. Preorder (Root, Left, Right) : 1 2 4 5 3
c. Postorder (Left, Right, Root) : 4 5 2 3 1

Breadth First or Level Order Traversal : 1 2 3 4 5

Algorithm :
1. Define class node including constructor
2. Define class tree including constructor
3. Display inorder , preorder and postroder traversals on constructed tree
Flowchart:

Test Cases:

Sr. Test Steps Input Expected Result Actual Result Statu s


NO ID (Pass/
Fail)

1 ID1 Construct a tree 10 20 30 Inorder traversal to Inorder traversal is Pass


and display be displayed displayed
inorder traversal 20 10 30
on it

2 ID2 Construct a tree 10 20 30 Preorder Preorder traversal is Pass


and traversal to be displayed
display preorder displayed 10 20 30
traversal on it

Conclusion: Successfully Tree traversals are implemented.


FAQs:
Q1. What is BFS (with example)

Q2. What is DFS (with example)

Q3. Which data structure is used in BFS

Q.4 What are the applications of BFS?

Q. 5 What are the applications of DFS?

Q.6 Write an algorithm to check whether the graph is strongly connected or not?

Q. 7 How can you say that the graph is strongly connected?

Q.8 What is topological sort using DAG?

Q.9 How the non-recursive implementation of DFS differs from the non-recursive implementation of
BFS?

Q.10 What are two ways to check whether graph is bipartite?

You might also like