0% found this document useful (0 votes)
100 views90 pages

Ok CMPE 30052 DATA STRUCTURES AND ALGORITHM 1

dsa module
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
0% found this document useful (0 votes)
100 views90 pages

Ok CMPE 30052 DATA STRUCTURES AND ALGORITHM 1

dsa module
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/ 90

CMPE30052

COMPILED BY:
ENGR.
CMPE-30052 JULIUS S. CANSINO ENGR. JULIAN L. LORICO
Page 1 ofJR.
90
ENGR. PEDRITO M. TENERIFE JR.
TABLE OF CONTENTS

MODULE 1: INTRODUCTION TO DATA STRUCTURES, SEARCHING AND SORTING .……………..3


Introduction to Data Structure ................................................................................................................. 3
Classification of Data Structure .............................................................................................................. 4
Abstract Data Type ................................................................................................................................. 5
Algorithm ................................................................................................................................................ 5
Searching Techniques ........................................................................................................................... 6
Sorting Techniques …………………………………………………………………………………………….7

Module 2: LINEAR DATA STRUCTURES ............................................................................................ 14


Stack Data Structure ............................................................................................................................ 14
Operations of stack .............................................................................................................................. 15
Evaluating arithmetic expressions ....................................................................................................... 17
Queue operations ................................................................................................................................. 18
Deques………………………………………………………………………………….................................20

Module 3: LINKED LIST ......................................................................................................................... 31


Linked list concepts .....……………………………………………………………………………………….31
Types of linked list...............................................................................................................................32
Operations in a single linked list……………………………………………………………………………..34

Module 4: NON-LINEAR DATA STRUCTURES ................................................................................... 49


Trees ..................................................................................................................................................... 49
Tree terminologies …………………………………………………………………………………………….50
Properties of Binary tree …………………………………………………………………………………..50
Binary tree traversal ………………………………………………………………………………………….52

Module 5: GRAPH AND ITS APPLICATIONS ...................................................................................... 59


Graph and its representatiions………………………………………………………………………………..59
Breadth first traversal………………………………………………………………………………………….61
Depth first traversal …………………………………………………………………………………………62
Module 6: BINARY TREES AND HASHING ......................................................................................... 68
Binary search tree ……………………………………………………………………………………………..68
Properties and operations …………………………………………………………………………………..69
Balanced search trees ………………………………………………………………………………………72
AVL trees ………………………………………………………………………………………………………73
Properties of AVL trees ………………………………………………………………………………………74

CMPE-30052 Page 2 of 90
MODULE 1: INTRODUCTION TO DATA STRUCTURES, SEARCHING
AND SORTING
Overview:
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. This tutorial
will give you a great understanding on Data Structures needed to understand the complexity of enterprise
level applications and need of algorithms, and data structures
(https://www.tutorialspoint.com/data_structures_algorithms/index.htm).

Module Objectives:
After successful completion of this module, you should be able to:
• understand the basics of data structure
• learn the various sorting algorithms
• explore how to implement the different sorting algorithm
• discover how the sorting algorithms perform

INTRODUCTION TO DATA STRUCTURES


A data structure is a way of storing data in a computer so that it can be used efficiently and it will
allow the most efficient algorithm to be used. The choice of the data structure begins from the choice of
an abstract data type (ADT). A well-designed data structure allows a variety of critical operations to be
performed, using as few resources, both execution time and memory space, as possible. Data structure
introduction refers to a scheme for organizing data, or in other words it is an arrangement of data in
computer's memory in such a way that it could make the data quickly available to the processor for
required calculations.

A data structure should be seen as a logical concept that must address two fundamental
concerns. First, how the data will be stored, and Second, what operations will be performed on it.
As data structure is a scheme for data organization so the functional definition of a data structure
should be independent of its implementation. The functional definition of a data structure is known as
ADT (Abstract Data Type) which is independent of implementation. The way in which the data is
organized affects the performance of a program for different tasks. Computer programmers decide
which data structures to use based on the nature of the data and the processes that need to be
performed on that data. Some of the more commonly used data structures include lists, arrays, stacks,
queues, heaps, trees, and graphs.

CMPE-30052 Page 3 of 90
CLASSIFICATION OF DATA STRUCTURES
Data structures can be classified as Simple, Compound, Linear and Non- Linear Data Structure

Fig 1.1 Classification of Data Structures

SIMPLE DATA STRUCTURE


Simple data structure can be constructed with the help of primitive data structure. A primitive data
structure used to represent the standard data types of any one of the computer languages. Variables,
arrays, pointers, structures, unions, etc. are examples of primitive data structures.

COMPOUND DATA STRUCTURE


Compound data structure can be constructed with the help of any one of the primitive data structure
and it is having a specific functionality. It can be designed by user. It can be classified as linear data
structure and Non-linear data structure

LINEAR DATA STRUCTURE


Linear data structures can be constructed as a continuous arrangement of data elements in the memory.
It can be constructed by using array data type. In the linear Data Structures, the relationship of adjacency
is maintained between the data elements.

OPERATIONS APPLIED ON LINEAR DATA STRUCTURE


The following list of operations applied on linear data structures
1. Add an element
2. Delete an element
3. Traverse
4. Sort the list of elements
5. Search for a data element
For example: Stack, Queue, Tables, List, and Linked Lists.

NON-LINEAR DATA STRUCTURE


Non-linear data structure can be constructed as a collection of randomly distributed set of data item
joined together by using a special pointer (tag). In non-linear Data structure the relationship of
adjacency is not maintained between the data items.

CMPE-30052 Page 4 of 90
OPERATIONS APPLIED ON NON-LINEAR DATA STRUCTURES:
The following list of operations applied on non-linear data structures.
1. Add elements
2. Delete elements
3. Display the elements
4. Sort the list of elements
5. Search for a data element
For example: Tree, Decision tree, Graph and Forest

ABSTRACT DATA TYPE


An abstract data type, sometimes abbreviated ADT, is a logical
description of how we view the data and the operations that are allowed
without regard to how they will be implemented. This means that we are
concerned only with what data is representing and not with how it will
eventually be constructed. By providing this level of abstraction, we are
creating an encapsulation around the data. The idea is that by
encapsulating the details of the implementation, we are hiding them from
the user’s view. This is called information hiding. The implementation of
an abstract data type, often referred to as a data structure, will require
that we provide a physical view of the data using some collection of
programming constructs and primitive data types. Fig. 1.2: Abstract Data
Type (right)

ALGORITHMS
STRUCTURE AND PROPERTIES OF ALGORITHM
An Algorithm has the following structure:
1. Input Step
2. Assignment Step
3. Decision Step
4. Repetitive Step
5. Output Step
An Algorithm has the following properties:
1. Finiteness: An algorithm must terminate after a finite number of steps.
2. Definiteness: The steps of the algorithm must be precisely defined or unambiguously specified.
3. Generality: An algorithm must be generic enough to solve all problems of a particular class.
4. Effectiveness: the operations of the algorithm must be basic enough to be put down on pencil
and paper. They should not be too complex to warrant writing another algorithm for the operation.
5. Input-Output: The algorithm must have certain initial and precise inputs, and outputs that may
be generated both at its intermediate and final steps.

DIFFERENT APPROACHES TO DESIGN AN ALGORITHM


An algorithm does not enforce a language or mode for its expression but only demands adherence to
its properties.

CMPE-30052 Page 5 of 90
SEARCHING TECHNIQUES
LINEAR SEARCH: Searching is a process of finding a
particular data item from a collection of data items based on
specific criteria. Every day we perform web searches to locate
data items containing in various pages. A search typically
performed using a search key and it answers either True or
False based on the item is present or not in the list. Linear
search algorithm is the simplest algorithm to do sequential
search and this technique iterates over the sequence and
checks one item at a time, until the desired item is found or all
items have been examined. In Python the in operator is used to find the desired item in a sequence of
items. The in operator makes searching task simpler and hides the inner working details.

Consider an unsorted single dimensional array of integers and we need to check whether 31 is present
in the array or not, then search begins with the first element. As the first element doesn't contain the
desired value, then the next element is compared to value 31 and this process continues until the desired
element is found in the sixth position. Similarly, if we want to search for 8 in the same array, then the
search begins in the same manner, starting with the first element until the desired element is found. In
linear search, we cannot determine that a given search value is present in the sequence or not until the
entire array is traversed.

BINARY SEARCH
In Binary search algorithm, the target key is examined in a sorted sequence and this algorithm starts
searching with the middle item of the sorted sequence.
a. If the middle item is the target value, then the search item is found and it returns True.
b. If the target item < middle item, then search for the target value in the first half of the list.
c. If the target item > middle item, then search for the target value in the second half of the list.

In binary search as the list is ordered, so we can


eliminate half of the values in the list in each
iteration. Consider an example, suppose we want
to search 10 in a sorted array of elements, then
we first determine the middle element of the
array. As the middle item contains 18,
which is greater than the target value 10,
so can discard the second half of the list
and repeat the process to first half of the
array. This process is repeated until the
desired target item is located in the list. If
the item is found then it returns True,
otherwise False.

CMPE-30052 Page 6 of 90
SORTING TECHNIQUES
Sorting in general refers to various methods of arranging or ordering things based on criteria's (numerical,
chronological, alphabetical, hierarchical etc.). There are many approaches to sorting data and each has
its own merits and demerits.

BUBBLE SORT
This sorting technique is also known as exchange sort, which arranges values by iterating over the list
several times and in each iteration the larger value gets bubble up to the end of the list. This algorithm
uses multiple passes and in each pass the first and second data items are compared. if the first data item
is bigger than the second, then the two items are swapped. Next the items in second and third position
are compared and if the first one is larger than the second, then they are swapped, otherwise no change
in their order. This process continues for each successive pair of data items until all items are sorted.
BUBBLE SORT ALGORITHM
Step 1: Repeat Steps 2 and 3 for i=1 to 10
Step 2: Set j=1
Step 3: Repeat while j<=n
(A) if a[i] < a[j]
Then interchange a[i] and a[j]
[End of if]
(B) Set j = j+1 [End of Inner loop]
[End of Step 1 Outer Loop]
Step 4: Exit
SELECTION SORT
Selection sort algorithm is one of the simplest
sorting algorithm, which sorts the elements in
an array by finding the minimum element in
each pass from unsorted part and keeps it in
the beginning. This sorting technique
improves over bubble sort by making only
one exchange in each pass. This sorting
technique maintains two sub arrays, one sub
array which is already sorted and the other
one which is unsorted. In each iteration the
minimum element (ascending order) is
picked from unsorted array and moved to
sorted sub array. Selection Sort Algorithm
is shown on the right

CMPE-30052 Page 7 of 90
INSERTION SORT
An algorithm considers the elements one at a time,
inserting each in its suitable place among those
already considered (keeping them sorted). Insertion
sort is an example of an incremental algorithm. It
builds the sorted sequence one number at a time.
Example of insertion sort is shown at the right

QUICK SORT
Quick sort is a divide and conquer algorithm. Quick sort first divides a large list into two smaller sub-lists:
the low elements and the high elements. Quick sort can then recursively sort the sub-lists. The steps are:

1. Pick an element, called a pivot, from the list.


2. Reorder the list so that all elements with values less than the pivot come before the pivot, while
all elements with values greater than the pivot come after it (equal values can go either way).
After this partitioning, the pivot is in its final position. This is called the partition operation.
3. Recursively apply the above steps to the sub-list of elements with smaller values and separately
the sub-list of elements with greater values.

The base case of the recursion is lists of size zero or one, which never need to be sorted.

MERGE SORT
Merge sort is based on Divide and conquer method. It takes the list to be sorted and divide it in half to
create two unsorted lists. The two unsorted lists are then sorted and merged to get a sorted list. The
two unsorted lists are sorted by continually calling the merge-sort algorithm; we eventually get a list of
size 1 which is already sorted. The two lists of size 1 are then merged.
MERGE SORT PROCEDURE
This is a divide and conquer algorithm.
This works as follows:
1. Divide the input which we have to sort into two parts in the middle. Call it the left part and right
part.
2. Sort each of them separately. Note that here sort does not mean to sort it using some other
method. We use the same function recursively.
3. Then merge the two sorted parts.

Input the total number of elements that are there in an array (number_of_elements). Input the array
(array[number_of_elements]). Then call the function MergeSort() to sort the input array. MergeSort()
function sorts the array in the range [left,right] i.e. from index left to index right inclusive. Merge () function
merges the two sorted parts. Sorted parts will be from [left, mid] and [mid+1, right]. After merging output,
the sorted array.

CMPE-30052 Page 8 of 90
Watch:
1. https://www.youtube.com/watch?v=xOuRE3IuEB8
2. https://www.youtube.com/watch?v=xLetJpcjHS0

Read:
1. https://www.studytonight.com/data-structures/introduction-to-data-structures
2. https://www.youtube.com/watch?v=JeznW_7DlB0
3. www.coelms.com

Review:
1. https://www.javatpoint.com/data-structure-tutorial
2.https://www.bing.com/videos/search?q=video+on+data+structure&ru=%2fvideos%2fsearch%3fq%3d
video%2bon%2bdata%2bstructure%26qpvt%3dvideo%2bon%2bdata%2bstructure%26FORM%3dVDR
E&view=detail&mid=D05312119A41DA386396D05312119A41DA386396&&FORM=VDRVRV

Activities/Assessments:

An organization contains a membership file in which each record contains the following data
for a given member: Name, Address, Telephone Number, Age, Sex.

Write the operation/s to be performed in completing a task given below:


1. Suppose the organization wants to announce a meeting through mail and wants
to obtain the names and address of each member.
2. Suppose one wants to find the names of all members living in a certain area.
3. Suppose one wants to obtain the Address for a given name.
4. Suppose a new person joins the organization and should be included in the list.
5. Suppose a member dies and the organization wants to update the record with
only members who are still alive.

CMPE-30052 Page 9 of 90
LABORATORY EXERCISE 1

A. ONE DIMENSIONAL ARRAY – Number Array

PROBLEM #01
Create a program that will ask the user to enter 10 numbers and display it in ascending order.

EXAMPLE PROGRAM OUTPUT:

PROBLEM #02
Create a program that will convert a decimal number (positive value) to its equivalent binary number.
• Use array for binary values

EXAMPLE PROGRAM OUTPUT:

PROBLEM #03
Create a program that will ask the user to enter 10 numbers and display the 1st and 2nd to
highest number and 1st and 2nd to the lowest number.
• Don’t use array sorting
EXAMPLE PROGRAM OUTPUT:

CMPE-30052 Page 10 of 90
B. One Dimensional Array: Array of Characters
PROBLEM #04
Create a program that will check if a given word is a palindrome or not a palindrome.

EXAMPLE PROGRAM OUTPUT:

CMPE-30052 Page 11 of 90
CMPE 30052 DATA STRUCTURE AND ALGORITHM
QUIZ No. 1
Name:______________________ Date:___________
Student No.:_________________ Score:__________

I. Essay. Briefly discuss the following: (5 points each)

1. Selection Sort
Answer:

2. Insertion Sort
Answer:

3. Bubble Sort
Answer:

4. Quick Sort
Answer:

5. Merge Sort
Answer:

CMPE-30052 Page 12 of 90
II. Application. Sort the following given value: 5,2,9,4,6 using the ff:
1. Insertion Sort 3. Bubble Sort

2. Selection Sort 4. Merge Sort

CMPE-30052 Page 13 of 90
MODULE 2: LINEAR DATA STRUCTURES
Overview:
Stack is a linear data structure which follows a particular order in which the operations are performed.
The order may be LIFO (Last In First Out) or FILO (First In Last Out).

Module Objectives:
After successful completion of this module, you should be able to:
• learn about stacks
• examine various stack operations
• learn how to implement a stack as an array and linked list
• discover stack applications

STACKS PRIMITIVE OPERATIONS


A stack is a container of objects that are inserted and removed
according to the last-in first-out (LIFO) principle. In the
pushdown stacks only two operations are allowed: push the
item into the stack, and pop the item out of the stack. A stack
is a limited access data structure - elements can be added
and removed from the stack only at the top. Push adds an
item to the top of the stack, pop removes the item from the
top. A helpful analogy is to think of a stack of books; you can
remove only the top book, also you can add a new book on
the top.

A stack may be implemented to have a bounded capacity. If


the stack is full and does not contain enough space to accept an entity to be pushed, the stack is then
considered to be in an overflow state. The pop operation removes an item from the top of the stack. A
pop either reveals previously concealed items or results in an empty stack, but, if the stack is empty, it
goes into underflow state, which means no items are present in stack to be removed.

STACK (ADT) DATA STRUCTURE


Stack is an Abstract data structure (ADT) works on the principle Last In First Out (LIFO). The last element
add to the stack is the first element to be delete. Insertion and deletion can be takes place at one end
called TOP. It looks like one side closed tube.

o The add operation of the stack is called push operation


o The delete operation is called as pop operation.
o Push operation on a full stack causes stack overflow.
o Pop operation on an empty stack causes stack underflow.
o SP is a pointer, which is used to access the top element of the stack.
o If you push elements that are added at the top of the stack;
o In the same way when we pop the elements, the element at the top of the stack is deleted.

CMPE-30052 Page 14 of 90
OPERATIONS OF STACK
There are two operations applied on stack they are the Push and the Pop. While performing Push &
Pop operations the following test must be conducted on the stack. First, Stack is empty or not. Second,
Stack is Full or not.
PUSH
Push operation is used to add new elements in to the stack. At the time of addition first check the stack
is full or not. If the stack is full it generates an error message "stack overflow".

POP
Pop operation is used to delete elements from the stack. At the time of deletion first check the stack
is empty or not. If the stack is empty it generates an error message "stack underflow".

REPRESENTATION OF A STACK USING ARRAYS


Let us consider a stack with 6 elements capacity. This is called as the size of the stack. The number of
elements to be added should not exceed the maximum size of the stack. If we attempt to add new element
beyond the maximum size, we will encounter a stack overflow condition. Similarly, you cannot remove
elements beyond the base of the stack. If such is the case, we will reach a stack underflow condition.

When a element is added to a stack, the operation is performed by push().

When an element is taken off from the stack, the operation is performed by pop().
STACK is a linear data structure which works under the principle of last in first out operations: push,
pop, display.

1. PUSH: if (top==MAX), display Stack overflow else reading the data and making stack [top]
=data and incrementing the top value by doing top++.

2. POP: if (top==0), display Stack underflow else printing the element at the top of the stack and
decrementing the top value by doing the top.

CMPE-30052 Page 15 of 90
3. DISPLAY: If (top==0), display Stack is empty else printing the
elements in the stack from stack [0] to stack [top].

LINKED LIST IMPLEMENTATION OF STACK


We can represent a stack as a linked list. In a stack push and pop operations are performed at one end
called top. We can perform similar operations at one end of list using top pointer.

STACK APPLICATIONS
1. Stack is used by compilers to check for balancing of parentheses, brackets and braces.
2. Stack is used to evaluate a postfix expression.
3. Stack is used to convert an infix expression into postfix/prefix form.
4. In recursion, all intermediate arguments and return values are stored on the processor‟s stack.
5. During a function call the return address and arguments are pushed onto a stack and on return
they are popped off.
6. Depth first search uses a stack data structure to find an element from a graph.

IN-FIX- TO POSTFIX TRANSFORMATION


Procedure to convert from infix expression to postfix expression is as follows:
Scan the infix expression from left to right.
A. If the scanned symbol is left parenthesis, push it onto the stack.
B. If the scanned symbol is an operand, then place directly in the postfix expression (output).
C. If the symbol scanned is a right parenthesis, then go on popping all the items from the stack
and place them in the postfix expression till we get the matching left parenthesis.
D. If the scanned symbol is an operator, then go on removing all the operators from the stack
and place them in the postfix expression, if and only if the precedence of the operator which
is on the top of the stack is greater than (or equal) to the precedence of the scanned operator and
push the scanned operator onto the stack otherwise, push the scanned operator onto the stack.

PRACTICE EXERCISES: Convert the following infix expression A + B * C – D / E * H into its equivalent
postfix expression.

SYMBOL POSTFIX STRING STACK REMARKS

A A

+ A +

B AB +

* AB +*

CMPE-30052 Page 16 of 90
C ABC -

- ABC*+ -

D ABC*+D -

/ ABC*+D -/

E ABC*+DE -/

* ABC*+DE/ -*

EVALUATING ARITHMETIC EXPRESSIONS


The postfix expression is evaluated easily by the use of a stack. When a number is seen, it is pushed
onto the stack; when an operator is seen, the operator is applied to the two numbers that are popped
from the stack and the result is pushed onto the stack.

EXAMPLE: Evaluate the postfix expression: 6 5 2 3 + 8 * + 3 + *

Symbol Operand 1 Operand 2 Value Stack Remarks

6 6

5 6, 5

2 6,5,2

3 6,5,2,3 The first four symbols are


placed on the stack.

Next a „+‟ is read, so 3 and 2


+ 2 3 5 6,5,5 are popped from the stack and
their sum 5, is pushed

8 2 3 5 6,5,5,8 Next 8 is pushed

Now a „*‟ is seen, so 8 and 5


* 5 8 40 6, 5, 40 are popped as 8 * 5 = 40 is
pushed

Next, a „+‟ is seen, so 40 and


+ 5 40 45 6, 45 5 are popped and 40 + 5 = 45
is pushed

3 5 40 45 6, 45, 3 Now, 3 is pushed

CMPE-30052 Page 17 of 90
+ 45 3 48 6, 48 Next, „+‟ pops 3 and 45 and
pushes 45 + 3 = 48 is pushed

Finally, a „*‟ is seen and 48


* 6 48 288 288 and 6 are popped, the result 6
* 48 = 288 is pushed

BASIC QUEUE OPERATIONS


A queue is a data structure that is best described as "first in, first out". A queue is another special kind
of list, where items are inserted at one end called the rear and deleted at the other end called the front.
A real world example of a queue is people waiting in line at the bank. As each person enters the bank,
he or she is "enqueued" at the back of the line. When a teller becomes available, they are "dequeued"
at the front of the line.

REPRESENTATION OF A QUEUE USING ARRAY

Let us consider a queue, which can hold maximum of five elements


(numbered 0 – 4 starting from the left). Initially the queue is empty.

QUEUE EMPTY
 FRONT = REAR = 0 F R

Now, insert 11 to the queue. Then queue status will be: 11

FRONT = 0
REAR = REAR + 1
 REAR = 1 F R

Next, insert 22 to the queue. Then the queue status is: 11 22

FRONT = 0
REAR= REAR +1
 REAR = 2 F R

CMPE-30052 Page 18 of 90
Again, insert another element 33 to the queue. The status of the queue 11 22 33
is:
∴FRONT = 0
REAR=REAR + 1 F R
∴REAR = 3

Now, delete an element. The element deleted is the element at the front 22 33
of the queue. So the status of the queue is:
∴REAR = 3
FRONT = FRONT + 1
∴ FRONT = 1 F R

Again, delete an element. The element to be deleted is always pointed


to by the FRONT pointer. So, 22 is deleted. The queue status is as 33
follows:
∴REAR = 3
FRONT = FRONT + 1 F R
∴FRONT = 2

Now, insert new elements 44 and 55 into the queue. The queue status 33 44 55
is:
∴REAR = 5
∴FRONT = 2
F R

Next insert another element, say 66 to the queue. We cannot insert 66 33 44 55


to the queue as the rear crossed the maximum size of the queue (i.e.,
5). There will be queue full signal. The queue status is as follows:
∴REAR = 5
͘∴FRONT = 2 F R

Now it is not possible to insert an element 66 even though there are 33 44 55 66


two vacant positions in the linear queue. To overcome this problem the
elements of the queue are to be shifted towards the beginning of the
queue so that it creates vacant position at the rear end. Then the
FRONT and REAR are to be adjusted properly. The element 66 can be
inserted at the rear end. After this operation, the queue status is as F R
follows:

CMPE-30052 Page 19 of 90
∴REAR = 4
∴FRONT = 0

This difficulty can overcome if we treat queue position with index 0 as a position that comes after position
with index 4 i.e., we treat the queue as a circular queue.

PROCEDURE FOR QUEUE OPERATIONS USING ARRAY


In order to create a queue we require a one dimensional array Q(1:n) and two variables front and rear.
The conventions we shall adopt for these two variables are that front is always 1 less than the actual front
of the queue and rear always points to the last element in the queue. Thus, front = rear if and only if there
are no elements in the queue. The initial condition then is front = rear = 0.

The various queue operations to perform creation, deletion and display the elements in a queue are as
follows:
1. insertQ(): inserts an element at the end of queue Q.
2. deleteQ(): deletes the first element of Q.
3. displayQ(): displays the elements in the queue.

Linked List Implementation of Queue: We can represent a queue as a linked list. In a queue data is
deleted from the front end and inserted at the rear end. We can perform similar operations on the two
ends of a list. We use two pointers front and rear for our linked queue implementation.

APPLICATIONS OF QUEUES
1. It is used to schedule the jobs to be processed by the CPU.
2. When multiple users send print jobs to a printer, each printing job is kept in the printing queue.
Then the printer prints those jobs according to first in first out (FIFO) basis.
3. Breadth first search uses a queue data structure to find an element from a graph.

DISADVANTAGES OF LINEAR QUEUE


There are two problems associated with linear queue. They are:
1. Time consuming: linear time to be spent in shifting the elements to the beginning of the queue.
2. Signaling queue full: even if the queue is having vacant position.

DEQUE (DOUBLE ENDED QUEUE)


A double-ended queue (dequeue, often abbreviated to deque, pronounced deck) generalizes a queue,
for which elements can be added to or removed from either the front (head) or back (tail).It is also often
called a head-tail linked list. Like an ordinary queue, a double-ended queue is a data structure it
supports the following operations: enq_front, enq_back, deq_front, deq_back, and empty.
Dequeue can be behave like a queue by using only enq_front and deq_front, and behaves like a stack
by using only enq_front and deq_rear.

CMPE-30052 Page 20 of 90
The DEQUE is represented as follows.

DEQUE can be represented in two ways they are


1. Input restricted DEQUE(IRD)
2. Output restricted DEQUE(ORD)

The output restricted DEQUE allows deletions from only one end and input restricted DEQUE allow
insertions at only one end. The DEQUE can be constructed in two ways they are using arrays and using
linked list.

OPERATIONS IN DEQUE
1. Insert element at back
2. Insert element at front
3. Remove element at front
4. Remove element at back

CMPE-30052 Page 21 of 90
Watch:
1. https://www.youtube.com/watch?v=a_agPzERnKI

Read:
1. https://www.studytonight.com/data-structures/introduction-to-data-structures
2. www.coelms.com

Review:
1. https://www.javatpoint.com/data-structure-tutorial

Activities/Assessments:

I. Consider the following stack of characters, where STACK is allocated N=8 memory cells:
STACK: A, C, D, F, K, ___, ___, ___
(For notational convenience, we use “___” to denote an empty memory cell). Draw the STACK as the
following operations take place:

A. POP (STACK, ITEM) E. POP(STACK, ITEM)


B. POP (STACK, ITEM) F. PUSH (STACK, R)
C. PUSH (STACK, L) G. PUSH (STACK, S)
D. PUSH (STACK, P) H. POP (STACK, ITEM)

II. Polish Notation. Translate the given expression as being required.

1. A + B ^ D / E –F + G ( Infix to Prefix and Postfix)


2. 12 , 7 , 3 , - , / , 2 , 1 , 5 , + , * , + ( Postfix to Infix)
3. + , / , + , A , ^ , B, D , - , E , F , G (Prefix to Infix)

CMPE-30052 Page 22 of 90
LABORATORY EXERCISE 2

A. User Defined Function: Void Function


PROBLEM #01
Create a program that will add, subtract, multiply and divide two numbers.
• Use user defined function for each operator
• Any number divided by zero will result to undefined
• Use int data type only for all variables declared

EXAMPLE PROGRAM OUTPUT:

CMPE-30052 Page 23 of 90
B. User Defined Function: Return Value
PROBLEM #02
Create a program compute the area of the following polygons and circle.
• Area of square given the side.
• Area of rectangle given the length and width.
• Area of triangle given the base and height.
• Area of circle given the radius.

EXAMPLE PROGRAM OUTPUT:

CMPE-30052 Page 24 of 90
C. Call by Value and Call by Reference
PROBLEM #03
Create a program that will compute the factorial of a given number.
• Use function to pass the value of the number input and to pass the reference of the factorial
value of the number.

EXAMPLE PROGRAM OUTPUT:

PROBLEM #4
Create a simple arithmetic calculator that will add, subtract, multiply and divide two integer
numbers.
• Use function to accept inputs for the two operands.

CMPE-30052 Page 25 of 90
EXAMPLE PROGRAM OUTPUT:

PROBLEM #5
Create a program that will overload a function named linechar that display a line of characters.
Use the given main function below:

int main()
{
linechar();
linechar('@');
linechar(10);
linechar('#',15);
system("pause>0");
return 0;
}

EXAMPLE PROGRAM OUTPUT:

CMPE-30052 Page 26 of 90
D. Pass by Array

PROBLEM #6
Create a program that will ask the user to enter ten numbers and get the sum of all odd
numbers.
• The numbers will be stored in array
• The array value will be pass as argument to the function

EXAMPLE PROGRAM OUTPUT:

D. Function Overloading and Pass by Array


PROBLEM #7
Create a program that will add two numbers, three numbers and four numbers. Use function
overloading named add.
• Use two arguments for adding two numbers
• Use three arguments for adding three numbers
• Use array with size 4 for adding four numbers
• The function add will return the value of the sum of the numbers

EXAMPLE PROGRAM OUTPUT:

CMPE-30052 Page 27 of 90
PROBLEM 8
Create a program that will overload a function named substring. The function will ask the user to
enter the index range of the substring inclusive. Using the function defined the program will display the
whole string value, the substring given the start index, and the substring given the start and last index.

EXAMPLE PROGRAM OUTPUT:

CMPE-30052 Page 28 of 90
CMPE 30052 DATA STRUCTURE AND ALGORITHM
QUIZ No. 1
Name:______________________ Score:___________________
Student No.:_________________ Course/Year:______________

I. Identification. Identify the following statement. (2 pts each)


_________1. It is a notation for writing arithmetic expressions in which operands appear
before the operator.
_________2. These are symbols use to by-passed precedence of operator.
_________3. It is a notation for writing arithmetic expressions in which operator appears
before the operands.
_________4. It is a notation for writing arithmetic expressions in which operator appears
between of operands.
_________5. The ADT algorithm used to convert infix to postfix.
_________6. It is an algorithm that implements FIFO.
_________7. It is an algorithm that implements LIFO.
_________8. It is a stack operation that allow user to add new data.
_________ 9. It is a queue operation that allow user to remove data.
_________ 10. It is also known as serve() function.

II. Conversion. Given the following infix expression, perform the following conversion.
(2 points
each)

Infix Expression Prefix Expression Postfix expression


1. (a-b)*(c+d)/e ______________________ ______________________

2. a-(b*c)+(d/e) ______________________ ______________________

3. a-(b*(c+d)/e ______________________ ______________________

4. (a-(b*c+d/e)) ______________________ ______________________

5. (a-b)*(c+d/e)) ______________________ ______________________

CMPE-30052 Page 29 of 90
III. Application. Given the expression, A+B-C*D/E, get the postfix expression using
stack implementation. (10 points)

Expression Stack Postfix String

CMPE-30052 Page 30 of 90
MODULE 3: LINKED LIST
Overview:
A linked list is a linear data structure, in which the elements are not stored at contiguous memory
locations. The elements in a linked list are linked using pointers. It consists of nodes where each node
contains a data field and a reference(link) to the next node in the list.

Module Objectives:
After successful completion of this module, you should be able to:
• learn about linked lists
• become aware of the basic properties of linked lists
• explore the insertion and deletion operations on linked lists
• discover how to build and manipulate a linked list

Linked lists and arrays are similar since they both store collections of data. Array is the most common
data structure used to store collections of elements. Arrays are convenient to declare and provide the
easy syntax to access any element by its index number. Once the array is set up, access to any
element is convenient and fast.

DISADVANTAGES OF ARRAYS
• The size of the array is fixed. Most often this size is specified at compile time. This makes the
programmers to allocate arrays, which seems "large enough" than required.
• Inserting new elements at the front is potentially expensive because existing elements need to
be shifted over to make room.
• Deleting an element from an array is not possible. Linked lists have their own strengths and
weaknesses, but they happen to be strong where arrays are weak.
• Generally, arrays allocate the memory for all its elements in one block whereas linked lists use
an entirely different strategy. Linked lists allocate memory for each element separately and only
when necessary.

LINKED LIST CONCEPTS


A linked list is a non-sequential collection of data items. It is a dynamic data structure. For every data
item in a linked list, there is an associated pointer that would give the memory location of the next data
item in the linked list. The data items in the linked list are not in consecutive memory locations. They
may be anywhere, but the accessing of these data items is easier as each data item contains the
address of the next data item.

ADVANTAGES OF LINKED LISTS


• Linked lists have many advantages. Some of the very important advantages are:
• Linked lists are dynamic data structures. i.e., they can grow or shrink during the execution of a
program.
• Linked lists have efficient memory utilization. Here, memory is not preallocated. Memory is
allocated whenever it is required and it is de-allocated (removed) when it is no longer needed.
• Insertion and Deletions are easier and efficient. Linked lists provide flexibility in inserting a data
item at a specified position and deletion of the data item from the given position.
• Many complex applications can be easily carried out with linked lists.

CMPE-30052 Page 31 of 90
DISADVANTAGES OF LINKED LISTS:
• It consumes more space because every node requires a additional pointer to store address of
the next node.
• Searching a particular element in list is difficult and also time consuming.

TYPES OF LINKED LISTS


Basically, we can put linked lists into the following four items namely Single, Double, Circular and
Circular Double Linked Lists.

• A single linked list is one in which all nodes are linked together in some sequential manner.
Hence, it is also called as linear linked list.

• A double linked list is one in which all nodes are linked together by multiple links which helps
in accessing both the successor node (next node) and predecessor node (previous node) from
any arbitrary node within the list. Therefore, each node in a double linked list has two link fields
(pointers) to point to the left node (previous) and the right node (next). This helps to traverse in
forward direction and backward direction.

• A circular linked list is one, which has no beginning and no end. A single linked list can be
made a circular linked list by simply storing address of the very first node in the link field of the
last node.

• A circular double linked list is one, which has both the successor pointer and predecessor
pointer in the circular manner.

CMPE-30052 Page 32 of 90
APPLICATIONS OF LINKED LIST
• Linked lists are used to represent and manipulate polynomial. Polynomials are expression
containing terms with non- zero coefficient and exponents. For example: P(x) = a0 Xn + a1 Xn - 1
+ …… + an-1 X + an
• Represent very large numbers and operations of the large number such as addition,
multiplication and division.
• Linked lists are to implement stack, queue, trees and graphs. 4. Implement the symbol table in
compiler construction.

SINGLE LINKED LIST


A linked list allocates space for each element separately in its own block of memory called a "node". The
list gets an overall structure by using pointers to connect all its nodes together like the links in a chain.
Each node contains two fields; a "data" field to store whatever element, and a "next" field which is a
pointer used to link to the next node. Each node is allocated in the heap using malloc(), so the node
memory continues to exist until it is explicitly de-allocated using free(). The front of the list is a pointer to
the “start” node.

CMPE-30052 Page 33 of 90
The beginning of the linked list is stored in a "start" pointer which points to the first node. The first node
contains a pointer to the second node. The second node contains a pointer to the third node, ... and so
on. The last node in the list has its next field set to NULL to mark the end of the list. Code can access
any node in the list by starting at the start and following the next pointers.
The start pointer is an ordinary local pointer variable, so it is drawn separately on the left top to show that
it is in the stack. The list nodes are drawn on the right to show that they are allocated in the heap.
The basic operations in a single linked list are
• Creation
• Insertion
• Deletion
• Traversing

CREATING A NODE FOR SINGLE LINKED LIST


Creating a singly linked list starts with creating a node. Sufficient memory has to be allocated for
creating a node. The information is stored in the memory.

INSERTION OF A NODE
One of the most primitive operations that can be done in a singly linked list is the insertion of a node.
Memory is to be allocated for the new node (in a similar way that is done while creating a list) before
reading the data. The new node will contain empty data field and empty next field. The data field of the

CMPE-30052 Page 34 of 90
new node is then stored with the information read from the user. The next field of the new node is
assigned to NULL. The new node can then be inserted at three different places namely:
• Inserting a node at the beginning

• Inserting a node at the end

• Inserting a node into the single linked list at a specified intermediate position other than
beginning and end.

CMPE-30052 Page 35 of 90
DELETION OF A NODE
Another primitive operation that can be done in a singly linked list is the deletion of a node. Memory is to
be released for the node to be deleted. A node can be deleted from the list from three different places
namely.
• Deleting a node at the beginning.

• Deleting a node at the end.

• Deleting a node at intermediate position.


The following steps are followed, to delete a node from an intermediate position in the list (List
must contain more than two node).

Traversal and displaying a list (Left to Right)


To display the information, you have to traverse (move) a linked list, node by node from the first node,
until the end of the list is reached.
Traversing a list involves the following steps:
• Assign the address of start pointer to a temp pointer.
• Display the information from the data field of each node. The function traverse () is used for
traversing and displaying the information stored in the list from left to right.

HEADER NODE USAGE


A header node is a special dummy node found at the front of the list. The use of header node is an
alternative to remove the first node in a list. For example, the picture below shows how the list with data
10, 20 and 30 would be represented using a linked list without and with a header node:

CMPE-30052 Page 36 of 90
Note that if your linked lists do include a header node, there is no need for the special case code given
above for the remove operation; node n can never be the first node in the list, so there is no need to
check for that case. Similarly, having a header node can simplify the code that adds a node before a
given node n.
Note that if you do decide to use a header node, you must remember to initialize an empty list to contain
one (dummy) node, you must remember not to include the header node in the count of "real" nodes in
the list.
It is also useful when information other than that found in each node of the list is needed. For example,
imagine an application in which the number of items in a list is often calculated. In a standard linked list,
the list function to count the number of nodes has to traverse the entire list every time. However, if the
current length is maintained in a header node, that information can be obtained very quickly. maximum
size of a list a head of time, you can pre-allocate the nodes in a single array. The result is a hybrid
structure – an array based linked list.
An example of null terminated single linked list where all the nodes are allocated contiguously in
an array.

CMPE-30052 Page 37 of 90
Watch:
1. https://www.youtube.com/watch?v=JlMyYuY1aXU

Read:
1. https://www.coelms.com

Review:
1. https://www.studytonight.com/data-structures/introduction-to-data-structures

Activities/Assessments:

Given below is a list of five hospital patients and their room numbers. (10 points)
A. Fill in values for NSTART and NLINK so that they form an alphabetical listing of the names(Ascending).
B. Fill in values for RSTART and RLINK so that they form an ordering of the room numbers.(Descending)

NSTART
NAME ROOM NLINK RLINK
1 Brown 650
2 Smith 422

RSTART 3 Adams 704


4 Jones 462
5 Burns 632
.

CMPE-30052 Page 38 of 90
LABORATORY EXERCISE 3
PROBLEM #1
Convert the predefined function strcmp() to user defined function.
Note: strcmp() returns three values based on the lexicographical order of the characters based on the
ASCII table

EXAMPLE PROGRAM OUTPUT:

PROBLEM #2
Convert the predefined function strcpy() to user defined function.

EXAMPLE PROGRAM OUTPUT:

PROBLEM #3
Convert the predefined function strcat() to user defined function.

EXAMPLE PROGRAM OUTPUT:

CMPE-30052 Page 39 of 90
PROBLEM #4
Convert a program that will determine if the given word input is a palindrome. The program will trim the
trailing spaces of the given word.

HINT: Create a user defined function for getting the length of the string and a string trim function for eliminating
trailing white spaces.

EXAMPLE PROGRAM OUTPUT:

B) Character Manipulation and String Class


PROBLEM #5
Create a program that will capitalize each word from the string input.

EXAMPLE PROGRAM OUTPUT:

CMPE-30052 Page 40 of 90
CMPE 30052 DATA STRUCTURES and ALGORITHM
MIDTERM EXAMINATION
Name Section Score

TEST I. MULTIPLE CHOICE. Choose the letter corresponding to the best choice. Use the answer sheet that has been
attached to this questionnaire. To register your answer, shade the appropriate oval/circle corresponding to each
number. Choose option “E” if in any case there’s no correct answer given on the selection set .

1. The set of native data types that a particular computer can support is determined by :
(a) type of hardware company
(b) what functions have been wired into hardware
(c) what software support is required
(d) None of these.

2. While considering data structure implementation, the factor(s) under consideration is (are) :
(a) time (b) time and space
(c) time, space and processor (d) None of these.

3. Which is not true?


(a) Abstract data type is the useful tool for specifying the logical properties of the data type
(b) While defining an abstract data type as a mathematical concept, the space and efficiency
is not of major concern
(c) Every abstract data type can be implemented using any programming language
(d) None of these.

4. Which of the following is (are) example(s) of data abstraction?


(a) List of student information (b) File of employee records
(c) Bank account database (d) All of the above.

5. Data structure means


(a) The separation of the representation of data from the applications that use the data at a
logical level
(b)the logical picture of a data type, plus the specifications of the operations required to
create and manipulate objects of this data type
(c)a collection of data elements whose organization is characterized by accessing
operations that are used to store and retrieve the individual data elements
(d) None of these.

6. Abstract Data Type means that

CMPE-30052 Page 41 of 90
(a) The separation of the representation of data from the applications that use the data at a logical
level
(b) The logical picture of a data type, plus the specifications of the operations required to create and
manipulate objects of this data type
(c) A collection of data elements whose organization is characterized by accessing operations that are
used to store and retrieve the individual data elements
(d) None of these.

7. Why is writing easily modifiable code important?


(a) Easily modifiable code generally has a quicker run time.
(b) Most real world programs require change at some time.
(c) Most text editors make it easy to modify code.
(d) Several people may be writing the same function at the same time.

8. What will happen if a function is executed and the precondition for the function is not met?
a. An error message will be printed. b. The program will loop indefinitely.
b. The system will crash. d. Any of the above results could happen

9. If the precondition fails, it is a good idea to write a useful error message and then halt the
program. Why is the program halted?
a. Most operating systems forbid continuation.
b. The function is no longer guaranteed to make the postcondition true.
c. The function's memory requires have become exponential (or worse).
d. The function's running time has become exponential (or worse).

11. What does a run-time analysis usually count?


a. The number of arithmetic and other operations required for the program to run
b. The number of megabytes required for the program to run
c. The number of seconds required for the program to run
d. The number of seconds plus the number of megabytes
e. The number of seconds times the number of megabytes

12. Example(s) of O(1) algorithms is (are):


(a) printing a character to the screen (b) incrementing a variable
(c) adding two numbers together (d) All of the above.

13. Example(s) of O(N) algorithms is (are):


(a) initializing all of the elements in an one-dimensional array to zero
(b) incrementing all the elements in an one-dimensional array
(c) multiplying two numbers by performing successive addition operations
(d) All of the above.

14. Example(s) of O(N2) algorithms is (are)


(a) initializing all the elements in a two dimensional array to zero
(b) printing out all the elements in a two dimensional array
(c) searching for the smallest element in an unsorted two-dimensional array
(d) All of the above.

CMPE-30052 Page 42 of 90
15. Three algorithms do the same task. Algorithm 1 is O(N2), Algorithm 2 is O(N), and Algorithm 3 is
O(Log2 N). Which algorithm should execute the fastest for large values of N?
(a) O(N) (b)O(N) (c)O(log2 N) (d) None of these.

16. Which of the following algorithm should execute the slowest for large values of N?
(a) O(N) (b) O(N2) (c) O(log2 N) (d) None of these.

17. What should never be found in the top level of a top-down design?
(a) Details (b) Coding (c) Decisions (d) None of these

18. Which of these is the correct big-O expression for 1+2+3+...+n?


a. O(log n) b. O(n) c. O(n log n) d. O(n²)

19. Which of the following formulas in big-O notation best represent the expression n²+35n+6?
a. O(n³) b. O(n²) c. O(n) d. O(42)

20. What term is used to describe an O(n) algorithm.


a. Constant b. Linear c. Logarithmic d. Quadratic

21. Here is some code for an integer variable n:


while (n > 0):
n = n/10 “Use integer division

What is the worst-case time analysis for the above loop?


a. O(1) b. O(log n) c. O(n) d. O(n²)

22. Express the formula (n - 2)*(n - 4) using big-O notation:


a. O(1) b. O(n2) c. O(log n) d. O(n)

23. Stack can be implemented by


(a) Array (b) Linked List (c) Both (a) and (b) (d) none of these

24. Consider the following four statements.


(i) A stack is an ordered collection of items into which new items may be inserted and from
which items may be deleted at the one end called top of the stack.
(ii) A stack is an ordered collection of items into which new items may be inserted into an
arbitrary location.
(iii) Dynamic implementation stacks using Java language are practically impossible.
(iv) One of the stack applications is used in complier design.
Which one of the following is correct in relation to the stacks?

(a) (i) and (iv) only (b) (i), (ii) and (iii) only
(c) (i) only (d) (iv) only

25. Consider the following infix expression: (( A+B) * C – (D-E)) ^ (F + G)


Which of the following is a / are correct equivalent expression(s) for the above?
(a) ^ - * + A B C – D E F G+ (b) ^ - * + A B C – D E F+ G
(c) ^ - * + A B C – D E + F G (d) - ^ * + A B C – D E + F G

CMPE-30052 Page 43 of 90
26. Which of the following statements is correct in connection with stacks?
(a) Return and remove the most recently inserted item from the stack, if stack is not empty.
(b) Insert a new item to the top of the stack, if stack is full.
(c) Elements can be deleted from both ends.
(d) Return and remove the least recently inserted item from the stack, if stack is not empty.

27. Which of the following is a / are possible operation(s) in connection with stacks?
(a) Reverse the order of elements on stack S using two additional stacks.
(b) Reverse the order of elements on stack S using additional variables.
(c) Reverse the order of elements on stack S using one stack and some additional queues.
(d) Sort the elements of stacks using one additional stack.

28. Evaluate the following prefix expression + * 2 + / 1 4 2 5 1


(a) 13 (b) 14 (c) 15 (d) 27

29. Evaluate the following prefix expression - * 6 3 – 4 1


(a) 25 (b) 15 (c) 23 (d) 12

30. Evaluate the following prefix expressions + + 2 6 + - 1 3 2 4


(a) 25 (b) 15 (c) 23 (d) 12

31. Convert the following infix expression to postfix notation (A + 2) * (B + 4) - 1


(a) A 2 + B 4 + * 1 - (b) – 1 * + 4 B + 2 A
(c) A 2 B 4 + + X l - (d) A 2 B 4 1 + + * -.

32. Convert the following infix expression to post fix notation Z – (((X + I) * 2) - 5)/Y
(a) Z X I + * 2 5 – / Y (b) Z X – I + 2 * 5 – Y I -
(c) Z X I + 2 * 5 – Y / - (d) Z X I + 2 5 * - Y /-.

33. A data structure in which an element is added and removed only from one end. is known
(a) queue (b) stack
(c) in-built data structure (d) None of these

34. “Get a node, store new element and insert the new node at the top" refers to insert operation in non-
empty
(a) stack (b) array (c) queue (d) None of these.

35. A data structure in which elements are added or removed only at a fixed end is known as
(a) queue (b) array (c) stack (d) Linked List.

36. One can convert an infix expression to a postfix expression using a


(a) stack (b) queue
(c) dequeue (d) none of these

37. The integers 1, 2, 3, 4 are pushed into the stack in that order. They may be popped out of the stack
in any valid order. The integers which are popped out produce a permutation of the numbers 1,2,3,4.
Which of the following permutation can never be produced in such a way?

CMPE-30052 Page 44 of 90
(a) 1,2,3,4. (b) 4,3,2, 1.
(c) 4, 2, 3. 1. (d) 3, 2,4, 1.

38. Which of the following types of expressions do not require precedence rules for evaluation?
(a) Fully parenthesized infix expression (b) Postfix expression
(c) Partially parenthesized infix expression (d) More than one of the above

39. Consider the following statements. Which of the following is TRUE.


(a) An expression in prefix form is the reverse of the same expression in postfix form.
(b) An expression in prefix form is the reverse of the same expression in postfix form if the
operators are +, * and /.
(c) None of the above.
(d) Both (a) & (b)

40. If the sequence of operations - push (1), push (2), pop, push (1) , push (2), pop, pop, pop, push (2),
pop, are performed on a stack, the sequence of popped out values are
(a) 2, 2, 1, 1, 2 (b) 2, 2, 1, 2, 2
(c) 2, 1, 2, 2, 1 (d) 2, 1, 2, 2, 2

41. In evaluating the arithmetic expression 2 * 3 - (4 + 5), using stacks to evaluate its equivalent post-fix
form, which of the following is stack output?
(a) -3 (b) 7
(c) 3 (d) 0

42. Stack A has the entries a, b, c (with a on top). Stack B is empty. An entry popped out of stack A can
be printed immediately or pushed to stack B. An entry popped out of stack B can only be printed. In this
arrangement, which of the following permutations of a, b, c is not possible?
(a) b a c (b) b c a (c) cab (d) a b c

Questions No. 43 and No. 44 are based on the following straight queue which can be allocated
eight integers and five operations.

front = 3 rear= 5
Queue = - , - , 2 , 4 ,5, - , - , -

(for notational convenience “ – “ used to denote an empty cell)


The following operations have to be performed.
(i) 6 is added to the queue.
(ii) Two elements are deleted from the queue.
(iii) 7 and 8 are added to the queue.
(iv) Two elements are deleted from the queue.
(v) 2 and 3 are added to the queue.

43. What are the final front and rear values when the above operations are performed into a straight
queue?

CMPE-30052 Page 45 of 90
(a) front = 7 rear=2 (b) front = 2 rear=7 (c) front = 7 rear=8 (d) front = 5 rear=8

44. What are the final front and rear values when the above operations are performed into a circular
queue?
(a) front = 7 rear=3 (b) front = 2 rear=7 (c) front = 2 rear=8 (d) front = 5 rear=8

45. The initial configuration of a queue is a, b, c, d, and a is in the front end. To get the configuration d,
c, b, a,
one needs a minimum of
(a) 2 deletions and 3 additions (b) 3 deletions and 2 additions
(c) 3 deletions and 3 additions (d) 3 deletions and 4 additions

46. Queue can be used to implement


(a) radix sort (b) quick sort (c) recursion (d) depth first search

47. The process of accessing data stored in a tape is similar to manipulating data on a
(a) stack (b) queue (c) list (d) heap

48. “FRONT = REAR” refers that a queue is


(a) Full (b) Empty (c) Circular (d) None of these

49. N elements of a queue are to be reversed using another queue. The number of “ADD” and
“REMOVE”
operations required to do so is
(a) 2*N (b) 4*N (c) N (d) the task can’t be
performed

50. In linked list, the logical order of elements


(a) is same as their physical arrangement.
(b) is determined by their physical arrangement.
(c) cannot be determined from their physical arrangement
(d) None of these

TEST II.
1. As shown in lecture 02, the structure of the list created by the following code: (2 points)

a_list = [4, 2, 6, 9, 3]

can be represented with the diagram:

Draw a diagram to show the structure of the list created by the code:

my_list = [[4], [2, 6, 9], [3]]

CMPE-30052 Page 46 of 90
2. In our lecture, you were shown diagrams that illustrated how different lists were represented in
memory. Use this approach to draw a diagram showing how the lists labelled e and f are
represented
in memory. (4 points)

a = [1]
b=a
c = [1, 2, 3]
d=c

e = [1, a, c]
f = [2, b, d]

3. What is the output of the following codes? (4 points)

my_list= LinkedList()
for x in[9, 2, 22, 40]:
my_list.add_to_head(x)
my_list.remove_from_tail()
my_list.add_to_tail(32)
my_list.remove_from_head()
my_list.remove_from_head()
my_list.add_to_head(100)
for num in my_list:
print(num, end=" ")

4. The following program uses a Car class to simulate a very simple race between a blue car and
a red car.
(40 points)
blue_car = Car('Blue')
red_car = Car('Red')

print(blue_car, red_car)

blue_car.accelerate(5)
red_car.accelerate(10)

print(blue_car, red_car)

if blue_car.is_faster(red_car):
print('Blue car faster')
else:
print('Blue car not faster')

CMPE-30052 Page 47 of 90
blue_car.accelerate(20)
red_car.accelerate(10)

print(blue_car, red_car)

if blue_car.is_faster(red_car):
print('Blue car faster')
else:
print('Blue car not faster')

class Car:

CMPE-30052 Page 48 of 90
MODULE 4: NON LINEAR DATA STRUCTURES
Overview:

The data structure where data items are not organized sequentially is called non linear data structure.
A data elements of the non linear data structure could be connected to more than one elements to reflect
a special relationship among them. All the data elements in non linear data structure can not be traversed
in single run.

Module Objectives:
After successful completion of this module, you should be able to:
• Learn about binary trees
• Explore various binary tree traversal algorithms
• Learn how to organize data in a binary search tree
• Discover how to insert and delete items in a binary search tree

TREES
A tree is a non-empty set one element of which
is designated the root of the tree while the
remaining elements are partitioned into non-
empty sets each of which is a sub-tree of the
root.

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 w.

Tree nodes have many useful properties. The depth of a node is the length of the path (or the number
of edges) from the root to that node. The height of a node is the longest path from that node to its leaves.
The height of a tree is the height of the root. A leaf node has no children -- its only path is up to its parent.

BINARY TREE
In a binary tree, each node can
have at most two children. A
binary tree node called the root
together with two binary trees
called the left subtree is either
empty or consists of and the
right subtree.

CMPE-30052 Page 49 of 90
TREE TERMINOLOGIES
LEAF NODE: A node with no children is called a leaf (or external node). A node which is not a leaf is
called an internal node.
PATH: A sequence of nodes n1, n2, . . ., nk, such that ni is the parent of ni + 1 for i = 1, 2,. . ., k - 1. The
length of a path is 1 less than the number of nodes on the path. Thus there is a path of length zero from
a node to itself.
SIBLINGS: The children of the same parent are called siblings.
ANCESTOR AND DESCENDENT: If there is a path from node A to node B, then A is called an
ancestor of B and B is called a descendent of A.
SUBTREE: Any node of a tree, with all of its descendants is
a subtree.
LEVEL: The level of the node refers to its distance from the
root. The root of the tree has level O, and the level of any
other node in the tree is one more than the level of its parent.
The maximum number of nodes at any level is 2n.
HEIGHT: The maximum level in a tree determines its height.
The height of a node in a tree is the length of a longest path
from the node to a leaf. The term depth is also used to denote height of the tree.
DEPTH: The depth of a node is the number of nodes along the path from the root to that node.

ASSIGNING LEVEL NUMBERS AND NUMBERING OF NODES FOR A BINARY TREE: The nodes of
a binary tree can be numbered in a natural way, level by level, left to right. The nodes of a complete
binary tree can be numbered so that the root is assigned the number 1, a left child is assigned twice the
number assigned its parent, and a right child is assigned one more than twice the number assigned its
parent.

PROPERTIES OF BINARY TREES


Some of the important properties of a binary tree are as follows:
1. If h = height of a binary tree, then
a. Maximum number of leaves = 2h
b. Maximum number of nodes = 2h + 1 - 1
2. If a binary tree contains m nodes at level l, it contains at most 2m nodes at level l + 1.
3. Since a binary tree can contain at most one node at level 0 (the root), it can contain at most 2 l
node at level l.
4. The total number of edges in a full binary tree with n node is n - 1.

STRICTLY BINARY TREE


If every non-leaf node in a binary tree has nonempty left and right subtrees,
the tree is termed a strictly binary tree. Thus the tree of figure 7.2.3(a) is
strictly binary. A strictly binary tree with n leaves always contains 2n -
1 nodes.

FULL BINARY TREE


A full binary tree of height h has all its leaves at level h. Alternatively;
All non-leaf nodes of a full binary tree have two children, and the leaf
nodes have no children.

CMPE-30052 Page 50 of 90
A full binary tree with height h has 2h + 1 - 1 nodes. A full binary tree of height h is a strictly binary tree all
of whose leaves are at level h.

For example, a full binary tree of height 3 contains 23+1 – 1 = 15 nodes.

COMPLETE BINARY TREE


A binary tree with n nodes is said to be complete if it contains all
the first n nodes of the above numbering scheme.

A complete binary tree of height h looks like a full binary tree


down to level h-1, and the level h is filled from left to right.

PERFECT BINARY TREE


A Binary tree is Perfect Binary Tree in which all internal
nodes have two children and all leaves are at same
level.

BALANCED BINARY TREE


A binary tree is balanced if height of the tree is O(Log n) where n is number of nodes. For Example, AVL
tree maintain O(Log n) height by making sure that the difference between heights of left and right subtrees
is 1. Red-Black trees maintain O(Log n) height by making sure that the number of Black nodes on every
root to leaf paths are same and there are no adjacent red nodes. Balanced Binary Search trees are
performance wise good as they provide O(log n) time for search, insert and delete.

REPRESENTATION OF BINARY TREES


1. Array Representation of Binary Tree
2. Pointer-based.

ARRAY REPRESENTATION OF BINARY TREE:


A single array can be used to represent a binary tree.
For these nodes are numbered / indexed according to a scheme giving 0 to root. Then all the nodes are
numbered from left to right level by level from top to bottom. Empty nodes are also numbered. Then each
node having an index i is put into the array as its ith element.

In the figure shown below the nodes of binary tree are numbered according to the given scheme.

CMPE-30052 Page 51 of 90
The figure shows how a binary tree is represented as an array. The root 3 is the 0 th element while its
leftchild 5 is the 1st element of the array. Node 6 does not have any child so its children i.e. 7th and 8th
element of the array are shown as a Null value.

It is found that if n is the number or index of a node, then its left child occurs at (2n + 1) th position and
right child at (2n + 2)th position of the array. If any node does not have any of its child, then null value is
stored at the corresponding index of the array.

Binary trees can be represented by links where each node contains


the address of the left child and the right child. If any node has its left
or right child empty then it will have in its respective link field, a null
value. A leaf node has null value in both of its links.

BINARY TREE TRAVERSALS


Traversal of a binary tree means to visit each node in the tree exactly
once. The tree traversal is used in all t it.

In a linear list nodes are visited from first to last, but a tree being a
nonlinear one we need definite rules. The ways to traverse a tree. All
of them differ only in the order in which they visit the nodes.

The three main methods of traversing a tree are Inorder Traversal,


Preorder Traversal and Postorder Traversal. In all of them we do not require to do anything to traverse
an empty tree. All the traversal
Methods are base functions since a binary tree is itself recursive as every child of a node in a binary tree
is itself a binary tree.

CMPE-30052 Page 52 of 90
INORDER TRAVERSAL
To traverse a non-empty tree in inorder the following
steps are followed recursively.
• Visit the Root
• Traverse the left subtree
• Traverse the right subtree

The inorder traversal of the tree shown on the right is as


follows.

PREORDER TRAVERSAL
Algorithm Pre-order(tree)
1. Visit the root.
2. Traverse the left sub-tree, i.e., call Pre-order(left-sub-tree)
3. Traverse the right sub-tree, i.e., call Pre-order(right-sub-tree)

POST-ORDER TRAVERSAL
Algorithm Post-order(tree)
1. Traverse the left sub-tree, i.e., call Post-order(left-sub-tree)
2. Traverse the right sub-tree, i.e., call Post-order(right-sub-tree)
3. Visit the root.

BINARY SEARCH TREE


Binary Search Tree, is a node-based binary tree data structure which has
the following properties:

The left sub-tree of a node contains only nodes with keys less than
the node’s key.

The right sub-tree of a node contains only nodes with keys greater
than the node’s key.

The left and right sub-tree each must also be a binary search tree.
There must be no duplicate nodes.

The above properties of Binary Search Tree provide an ordering among keys so that the operations
like search, minimum and maximum can be done fast. If there is no ordering, then we may have to
compare every key to search a given key.

SEARCHING A KEY
To search a given key in Binary Search Tree, we first compare it with root, if the key is present at root,
we return root. If key is greater than root’s key, we recur for right sub-tree of root node. Otherwise we
recur for left sub-tree.

# A utility function to search a given key in BST def search(root,key):


# Base Cases: root is null or key is present at root
if root is None or root.val == key:
return root

CMPE-30052 Page 53 of 90
# Key is greater than root's key if root.val < key:
return search(root.right,key)
#Key is smaller than root's key return
search(root.left,key)

Watch:
1. https://www.youtube.com/watch?v=qH6yxkw0u78

Read:
1. https://www.coelms.com
2. https://www.studytonight.com/data-structures/introduction-to-data-structures

Review:
1. https://www.youtube.com/watch?v=qH6yxkw0u78

Activities/Assessments:

Consider the binary search tree. Draw the tree if each of the following operations is applied to the
original tree. (That is, the operations are applied independently, not successively).
A. Node 20 is added to the tree
50
B. Node 15 is added to the tree
C. Node 88 is added to the tree
25 75
D. Node 22 is deleted to the tree
E. Node 25 is deleted to the tree
F. Node 75 is deleted to the tree 22 40 60 90

15 80
30 44

33

CMPE-30052 Page 54 of 90
LABORATORY EXERCISE 4

1. Create a programmer defined function that will do the same as strcpy function.

2. Create a programmers defined function that will do the same as strcmp function.

3. Create a programmers defined function that will do the same as strcat function.

4. Create a programmers defined function that will do the same as strlen function.

5. Create a program that will return a reverse string using pointer.

CMPE-30052 Page 55 of 90
CMPE 30052 DATA STRUCTURES AND ALGORITHM
QUIZ No. 2

Name _____________________________ Date: __________________


Year/Section:________________________ Score:_________________

BINARY EXPRESSION TREE


Solve these binary expressions for the numerical answer(using integer math) and draw their respective
expression trees.

1.) + * + 2 5 3 - 7 1 _____ 2.) - * / 8 3 6 - + 5 9 4 _____

3.) 7 4 + 3 * 8 9 - + _____ 4.) 6 5 * 1 7 - 2 7 + 8 5 * + - + _____

5. Translate this binary expression tree into an infix, prefix, and postfix algebraic expression.
Then solve the numerical answer using any method. Use integer math.

* + 2

4 3 3 *

2 4

Infix: ___________________________________________________________
Prefix: ___________________________________________________________
Postfix: ___________________________________________________________
Answer: __________

CMPE-30052 Page 56 of 90
6. Translate this binary expression tree into an infix, prefix, and postfix algebraic expression.
Then solve the numerical answer using any method. Use integer math.

* 9

3 +

- 6

+ *

2 7 3 8

Infix: ___________________________________________________________
Prefix: ___________________________________________________________
Postfix: ___________________________________________________________
Answer: __________

7. In class, we saw how to build a BET from a Prefix expression.

Build the BET from


/+-*12+*-345678 Evaluate: ____________(int math)

Now, see if you can follow the same logic and build a BET from these POSTfix expressions:
6 5 – 3 4 + * Evaluate: ____________(int math)

8 7 – 6 5 4 3 + + + 2 1 / * + Evaluate: ____________(int math)

CMPE-30052 Page 57 of 90
CMPE 30052 DATA STRUCTURE AND ALGORTIHM
Quiz No. 3
Name:______________________ Date:_________________
Student No.:_________________ Score:________________

I. Identification. Identify the following statements: (2 pts each)


_____________ 1. It is a programming technique in which procedures and functions call
themselves.
_____________ 2. It is the case for which the solution is expressed in smaller version of itself.
_____________ 3. It is the case for which the solution can be stated non-recursively.
_____________ 4. A recursive function which contains only one recursive call appears in the
function
and that recursive call is the last statement in the function body.
_____________5. Whenever a function is called, a block of memory is allocated to it in a run-
time
structure.
_____________6. A tree is a collection of nodes.
_____________7. It is the mother node of a tree structure.
_____________8. It is the immediate predecessor of a node.
_____________9. The line drawn from one node to other node.
_____________10. A node without a child.
_____________11. The highest number of nodes that is possible in a way starting from the
first node
to a leaf node.
_____________12. These are nodes that share the same parent.
_____________13. It is a group of disjoint trees.
_____________14. The simplest form of tree.
_____________15. It is a tree where every non-leaf node in binary tree is filled with left and
right sub-
trees.

II. Application. Given the values, 5,5,1,9,8,5 create and draw the binary search tree and
answer the following:

_____________ 1. Root Node


_____________ 2. Siblings of 5
_____________ 3. Parent of 5
_____________ 4. Height of a Tree
_____________ 5. Level of a Tree
_____________ 6. Leaf Nodes
_____________ 7. Ancestors of 5
_____________ 8. Children of 5
_____________ 9. Depth of 5
_____________ 10. Path form Node 8 to Node 5

CMPE-30052 Page 58 of 90
MODULE 5: GRAPH AND ITS APPLICATIONS
Overview:
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also
referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph.

Module Objectives:
After successful completion of this module, you should be able to:
• describe a graph
• understand how to implement a graph
• describe algorithms to traverse a graph

GRAPH
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.

GRAPH AND ITS REPRESENTATIONS


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. Shown in the right is
an example undirected graph with 5 vertices.

The two most commonly used representation of graphs is the Adjacency Matrix and 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.

CMPE-30052 Page 59 of 90
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 shown on the right

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 ith vertex. This
representation can also be used to represent a
weighted graph. The weights of edges can be
stored in nodes of linked lists. The adjacency list
representation of the above graph is shown on the
right.

CMPE-30052 Page 60 of 90
Algorithm: Breadth-First Search Traversal
BFS(V, E, s)
BREADTH FIRST TRAVERSAL FOR A for each u in V − {s}
GRAPH do color[u] ← WHITE
Breadth First Traversal (or Search) for a graph is d[u] ← infinity
similar to Breadth First Traversal of a tree The only π[u] ← NIL
catch here is, unlike trees, graphs may contain color[s] ← GRAY
cycles, so we may come to the same node again. To
d[s] ← 0
avoid processing a node more than once, we use a
π[s] ← NIL
boolean visited array.
Q←{}
For example, in the following graph, we start ENQUEUE(Q, s)
while Q is non-empty
traversal from vertex 2. When we come to vertex 0,
do u ← DEQUEUE(Q)
we look for all adjacent vertices of it. 2 is also an
adjacent vertex of 0. If we don’t mark visited vertices, for each v adjacent to u
then 2 will be processed again and it will become a do if color[v] ← WHITE
then color[v] ← GRAY
non-terminating process. Breadth First Traversal of
d[v] ← d[u] + 1
the following graph is 2, 0, 3, 1
π[v] ← u
ENQUEUE(Q, v)
DEQUEUE(Q)
color[u] ← BLACK

APPLICATIONS OF BREADTH FIRST TRAVERSAL


1. Shortest Path and Minimum Spanning Tree for unweighted graph In unweighted graph, the
shortest path is the path with least number of edges. With Breadth First, we always reach a vertex from
given source using minimum number of edges. Also, in case of unweighted graphs, any spanning tree is
Minimum Spanning Tree and we can use either Depth or Breadth first traversal for finding a spanning
tree.

2. Peer to Peer Networks. In Peer to Peer Networks like Bit Torrent, Breadth First Search is used to find
all neighbor nodes.

3. Crawlers in Search Engines: Crawlers build index using Bread First. The idea is to start from source
page and follow all links from source and keep doing same. Depth First Traversal can also be used for
crawlers, but the advantage with Breadth First Traversal is, depth or levels of built tree can be limited.

4. Social Networking Websites: In social networks, we can find people within a given distance ‘k’ from
a person using Breadth First Search till ‘k’ levels.

5. GPS Navigation systems: Breadth First Search is used to find all neighboring locations.

6. Broadcasting in Network: In networks, a broadcasted packet follows Breadth First Search to reach
all nodes.

7. In Garbage Collection: Breadth First Search is used in copying garbage collection using Cheney’s
algorithm.

CMPE-30052 Page 61 of 90
8. Cycle detection in undirected graph: In undirected graphs, either Breadth First Search or Depth
First Search can be used to detect cycle. In directed graph, only depth first search can be used.

9. Ford–Fulkerson algorithm In Ford-Fulkerson algorithm, we can either use Breadth First or Depth
First Traversal to find the maximum flow. Breadth First Traversal is preferred as it reduces worst case
time complexity to O(VE2).
10. To test if a graph is Bipartite We can either use Breadth First or Depth First Traversal.

11. Path Finding We can either use Breadth First or Depth First Traversal to find if there is a path
between two vertices.

12. Finding all nodes within one connected component: We can either use Breadth First or Depth
First Traversal to find all nodes reachable from a given node.

DEPTH FIRST TRAVERSAL FOR A GRAPH


Depth First Traversal (or Search) for
a graph is similar to Depth First
Traversal of a tree. The only catch
here is, unlike trees, graphs may
contain cycles, so we may come to
the same node again. To avoid
processing a node more than once,
we use a Boolean visited array. For
example, in the following graph, we
start traversal from vertex 2. When
we come to vertex 0, we look for all
adjacent vertices of it. 2 is also an
adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become
a non-terminating process. Depth First Traversal of the following graph is 2, 0, 1, 3

ALGORITHM DEPTH-FIRST SEARCH


The DFS forms a depth-first forest comprised of more than one depth-first trees. Each tree is made of
edges (u, v) such that u is gray and v is white when edge (u, v) is explored. The following pseudocode
for DFS uses a global timestamp time.

CMPE-30052 Page 62 of 90
DFS (V, E)
ALGORITHM DEPTH-FIRST SEARCH for each vertex u in V[G]
The DFS forms a depth-first forest comprised of more than do color[u] ← WHITE
one depth-first trees. Each tree is made of edges (u, v) such π[u] ← NIL
that u is gray and v is white when edge (u, v) is explored. The time ← 0
following pseudocode for DFS uses a global timestamp time. for each vertex u in V[G]
do if color[u] ← WHITE
APPLICATIONS OF DEPTH FIRST SEARCH then DFS-Visit(u)
Depth-first search (DFS) is an algorithm (or technique) for
traversing a graph. DFS-Visit(u)
Following are the problems that use DFS as a building block. color[u] ← GRAY
time ← time + 1
1) For an unweighted graph, DFS traversal of the graph d[u] ← time
produces the minimum spanning tree and all pair shortest for each vertex v adjacent to u
path tree.
do if color[v] ← WHITE
2) Detecting cycle in a graph then π[v] ← u
A graph has cycle if and only if we see a back edge during DFS-Visit(v)
DFS. So we can run DFS for the graph and check for back color[u] ← BLACK
edges. (See this for details) time ← time + 1
f[u] ← time
3) Path Finding
We can specialize the DFS algorithm to find a path between
two given vertices u and z.
1. Call DFS (G, u) with u as the start vertex.
2. Use a stack S to keep track of the path between the start vertex and the current vertex.
3. As soon as destination vertex z is encountered, return the path as the
contents of the stack

4) Topological Sorting

5) To test if a graph is bipartite


We can augment either BFS or DFS when we first discover a new vertex, color it opposite its parents,
and for each other edge, check it doesn’t link two vertices of the same color. The first vertex in any
connected component can be red or black! See this for details.

6) Finding Strongly Connected Components of a graph A directed graph is called strongly


connected if there is a path from each vertex in the graph to every other vertex. (See this for DFS based
also for finding Strongly Connected Components)

DFS search starts from root node then traversal into left child node and continues, if item found it stops
otherwise it continues. The advantage of DFS is it requires less memory compare to Breadth First
Search (BFS).

BFS search starts from root node then traversal into next level of graph or tree and continues, if item
found it stops otherwise it continues. The disadvantage of BFS is it requires more memory compare to
Depth First Search (DFS).

CMPE-30052 Page 63 of 90
Watch:
1. https://www.youtube.com/watch?v=gXgEDyodOJU

Read:
1. https://www.coelms.com
2. https://www.studytonight.com/data-structures/introduction-to-data-structures

Review:
1. https://www.studytonight.com/data-structures/introduction-to-data-structures

Activities/Assessments:
I. Consider the undirected graph given below (20 points)
A. Find all simple path from node A to node H.
B. Adjacency matrix

A B C D

E F G H

CMPE-30052 Page 64 of 90
LABORATORY EXERCISE 5
Problem 1:

Create a program that will ask the user to enter the student record with three quizzes. The program will
display the student record together with the average grade of the three quizzes and display a remark if
the student passed the subject or not. The structure must compose of thee members the id, the name,
and the quiz in array form.

Output:

Case 1: Case 2:

Problem 2:

Create a program that will enter 5 student records with three quizzes. The program will generate an
output that will displays all the student records with their grades and remarks.
grades = average grade of the three quizzes
75 is the passing mark.

CMPE-30052 Page 65 of 90
OUTPUT

Problem 3:

Create a program that will give an output as shown on figure A.The program will ask to input three
customers information. Each customer have three items purchased. Used the given structure below.

Customer Name Order Item


name (structure) lastName date (w or w/o ID or Code
contactNo firstName structure) Name
order (structure) item (structure) Price
quantity

Date
day
month
year

CMPE-30052 Page 66 of 90
CMPE-30052 Page 67 of 90
MODULE 6: BINARY TREES AND HASHING
Overview:

Binary Search Tree is a node-based binary tree data structure which has the following properties:

• The left subtree of a node contains only nodes with keys lesser than the node’s key.
• The right subtree of a node contains only nodes with keys greater than the node’s key.
• The left and right subtree each must also be a binary search tree.

Module Objectives:
After successful completion of this module, you should be able to:
• learn about binary search trees
• explore various binary search tree properties and operations
• implement set (ADT) using BST

BINARY SEARCH TREES


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.

In other words, binary search trees are binary trees in which all values in the node’s left subtree are less
than node value all values in the node’s right subtree are greater than node value.

Here are some BSTs in which each node just stores an integer key:

These are not BSTs:

CMPE-30052 Page 68 of 90
In the left one 5 is not greater than 6. In the right
one 6 is not greater than 7. The reason binary-
search trees are important is that the following
operations can be implemented efficiently using
a BST:
▪ insert a key value
▪ determine whether a key value is in the
tree
▪ remove a key value from the tree
▪ print all of the key values in sorted order

Let's illustrate what happens using the following BST and searching for 12:

Let's illustrate what happens using the following


BST and searching for 15:

PROPERTIES AND OPERATIONS


A BST is a binary tree of nodes ordered in the following way:
1. Each node contains one key (also unique)
2. The keys in the left subtree are < (less) than the key in its parent node
3. The keys in the right subtree > (greater) than the key in its parent node
4. Duplicate node keys are not allowed.

INSERTING A NODE
A naïve algorithm for inserting a node into a BST is that, we start from the root node, if the node to insert
is less than the root, we go to left child, and otherwise we go to the right child of the root. We continue
this process (each node is a root for some sub tree) until we find a null pointer (or leaf node) where we
cannot go any further. We then insert the node as a left or right child of the leaf node based on node is
less or greater than the leaf node. We note that a new node is always inserted as a leaf node. A recursive
algorithm for inserting a node into a BST is as follows. Assume we insert a node N to tree T. if the tree is
empty, the we return new node N as the tree. Otherwise, the problem of inserting is reduced to inserting
the node N to left of right sub trees of T, depending on N is less or greater than T. A definition is as
follows.

Insert(N, T) = N if T is empty
= insert(N, T.left) if N < T

CMPE-30052 Page 69 of 90
= insert(N, T.right) if N > T

SEARCHING FOR A NODE


Searching for a node is similar to inserting a node. We start from root, and then go left or right until we
find (or not find the node). A recursive definition of search is as follows. If the node is equal to root, then
we return true. If the root is null, then we return false. Otherwise we recursively solve the problem for
T.left or T.right, depending on N < T or N > T. A recursive definition is as follows. Search should return
a true or false, depending on the node is found or not.
Search(N, T) = false if T is empty
= true if T = N
= search(N, T.left) if N < T
= search(N, T.right) if N > T

DELETING A NODE
A BST is a connected structure. That is, all nodes in a tree are connected to
some other node. For example, each node has a parent, unless node is the
root. Therefore, deleting a node could affect all sub trees of that node. For
example, deleting node 5 from the tree could result in losing sub trees that are
rooted at 1 and 9.

Hence we need to be careful about deleting nodes from a tree. The best way
to deal with deletion seems to be considering special cases. What if the node
to delete is a leaf node? What if the node is a node with just one child? What
if the node is an internal node (with two children)? The latter case is the hardest
to resolve. But we will find a way to handle this situation as well.

CASE 1: The node to delete is a leaf node


This is a very easy case. Just delete the node 46. We are done

CMPE-30052 Page 70 of 90
CASE 2: The node to delete is a node with one child.
This is also not too bad. If the node to be deleted is a left child of the parent,
then we connect the left pointer of the parent (of the deleted node) to the
single child. Otherwise if the node to be deleted is a right child of the parent,
then we connect the right pointer of the parent (of the deleted node) to single
child.

CASE 3: The node to delete is a node with two children


This is a difficult case as we need to deal with two sub trees. But we find
an easy way to handle it. First we find a replacement node (from leaf
node or nodes with one child) for the node to be deleted. We need to do
this while maintaining the BST order property. Then we swap leaf node
or node with one child with the node to be deleted (swap the data) and
delete the leaf node or node with one child (case 1 or case 2)

Next problem is finding a replacement leaf node for the node to be


deleted. We can easily find this as follows. If the node to be deleted is
N, the find the largest node in the left sub tree of N or the smallest node
in the right sub tree of N. These are two candidates that can replace the
node to be deleted without losing the order property. For example,
consider the following tree and suppose we need to delete the root 38.

Then we find the largest


node in the left sub tree
(15) or smallest node in
the right sub tree (45) and
replace the root with that
node and then delete that
node. The following set of
images demonstrates this
process.

Let’s see when we delete 13 from that tree.

CMPE-30052 Page 71 of 90
BALANCED SEARCH TREES
A self-balancing (or height-balanced) binary search tree is any node-based binary search tree that
automatically keeps its height (maximal number of levels below the root) small in the face of arbitrary
item insertions and deletions. The red–black tree, which is a type of self-balancing binary search tree,
was called symmetric binary B-tree. Self-balancing binary search trees can be used in a natural way to
construct and maintain ordered lists, such as priority queues. They can also be used for associative
arrays; key-value pairs are simply inserted with an ordering based on the key alone. In this capacity, self-
balancing BSTs have a number of advantages and disadvantages over their main competitor, hash
tables. One advantage of self-balancing BSTs is that they allow fast (indeed, asymptotically optimal)
enumeration of the items in key order, which hash tables do not provide. One disadvantage is that their
lookup algorithms get more complicated when there may be multiple items with the same key. Self-
balancing BSTs have better worst-case lookup performance than hash tables (O(log n) compared to
O(n)), but have worse average-case performance (O(log n) compared to O(1)).

CMPE-30052 Page 72 of 90
Self-balancing BSTs can be used to implement any algorithm that requires mutable ordered lists, to
achieve optimal worst-case asymptotic performance. For example, if binary tree sort is implemented with
a self-balanced BST, we have a very simple-to-describe yet asymptotically optimal O(n log n) sorting
algorithm. Similarly, many algorithms in computational geometry exploit variations on self-balancing
BSTs to solve problems such as the line segment intersection problem and the point location problem
efficiently. (For average-case performance, however, self-balanced BSTs may be less efficient than other
solutions. Binary tree sort, in particular, is likely to be slower than merge sort, quicksort, or heapsort,
because of the tree-balancing overhead as well as cache access patterns.)

Self-balancing BSTs are flexible data structures, in that it's easy to extend them to efficiently record
additional information or perform new operations. For example, one can record the number of nodes in
each subtree having a certain property, allowing one to count the number of nodes in a certain key range
with that property in O(log n) time. These extensions can be used, for example, to optimize database
queries or other list-processing algorithms.

AVL TREES
An AVL tree is another balanced binary search tree. Named after their inventors, Adelson-Velskii and
Landis, they were the first dynamically balanced trees to be proposed. Like red-black trees, they are not
perfectly balanced, but pairs of sub-trees differ in height by at most 1, maintaining an O(logn) search
time. Addition and deletion operations also take O(logn) time.

DEFINITION OF AN AVL TREE: An AVL tree is a binary


search tree which has the following properties: First, The
sub-trees of every node differ in height by at most one.
Second, Every sub-tree is an AVL tree.

Balance requirement for an AVL tree: the left and right sub-
trees differ by at most 1 in height.

Yes this is an AVL tree. Examination shows that each left sub-
tree has a height 1 greater than each right sub-tree.

CMPE-30052 Page 73 of 90
No this is not an AVL tree. Sub-tree with root 8 has height 4
and sub-tree with root 18 has height 2.

An AVL tree implements the Map abstract data type just like a regular binary search tree, the only
difference is in how the tree performs. To implement our AVL tree we need to keep track of a balance
factor for each node in the tree. We do this by looking at the heights of the left and right subtrees for
each node. More formally, we define the balance factor for a node as the difference between the height
of the left subtree and the height of the right subtree.

balanceFactor=height(leftSubTree)−height(rightSubTree)

PROPERTIES OF
AVL TREES
AVL trees are identical to standard binary search trees except
that for every node in an AVL tree, the height of the left and right
subtrees can differ by at most 1 (Weiss, 1993, p:108). AVL trees
are HB-k trees (height balanced trees of order k) of order HB-1.

The following is the height differential formula:

When storing an AVL tree, a field must be added to each node


with one of three values: 1, 0, or -1. A value of 1 in this field means that the left subtree has a height one
more than the right subtree. A value of -1 denotes the opposite. A value of 0 indicates that the heights
of both
subtrees are the same. Updates of AVL trees require up to rotations, whereas updating

CMPE-30052 Page 74 of 90
red-black trees can be done using only one or two rotations (up to color changes). For this
reason, they (AVL trees) are considered a bit obsolete by some.

SPARSE AVL TREES


Sparse AVL trees are defined as AVL trees of height h with the fewest possible nodes. Figure 3
shows sparse AVL trees of heights 0, 1, 2, and 3.

INTRODUCTION TO M-WAY SEARCH TREES


A multiway tree is a tree that can have more than two children. A multiway tree of order m (or an m-
way tree) is one in which a tree can have m children.

As with the other trees


that have been studied,
the nodes in an m-way
tree will be made up of
key fields, in this case
m-1 key fields, and
pointers to children.
Shown on the right is a
Multiday tree of order 5

To make the processing of m-way trees easier some type of order will be imposed on the keys within
each node, resulting in a multiway search tree of order m (or an m-way search tree). By definition an
m-way search tree is a m-way tree in which:

Each node has m children and m-1 key fields


The keys in each node are in ascending order.
The keys in the first i children are smaller than the ith key
The keys in the last m-i children are larger than the ith key

The figure shown on the right is an example


of a 4-Way Search Tree
M-way search trees give the same
advantages to m-way trees that binary
search trees gave to binary trees - they
provide fast information retrieval and update.
However, they also have the same problems
that binary search trees had - they can
become unbalanced, which means that the
construction of the tree becomes of vital
importance.

B TREES
An extension of a multiway search tree of order m is a B-tree of order m. This type of tree will be used
when the data to be accessed/stored is located on secondary storage devices because they allow for
large amounts of data to be stored in a node.

CMPE-30052 Page 75 of 90
A B-tree of order m is a multiway search tree in which:
1. The root has at least two subtrees unless it is the only node in the tree.
2. Each nonroot and each nonleaf node have at most m nonempty children and at least m/2
nonempty children.
3. The number of keys in each nonroot and each nonleaf node is one less than the number of its
nonempty children.
4. All leaves are on the same level.

These restrictions make B-trees always at least half full, have few levels, and remain perfectly balanced.

SEARCHING A B-TREE
An algorithm for finding a key in B-tree is simple. Start at the root and determine which pointer to follow
based on a comparison between the search value and key fields in the root node. Follow the appropriate
pointer to a child node. Examine the key fields in the child node and continue to follow the appropriate
pointers until the search value is found or a leaf node is reached that doesn't contain the desired search
value.

INSERTION INTO A B-TREE


The condition that all leaves must be on the same level forces a characteristic behavior of B-trees, namely
that B-trees are not allowed to grow at the their leaves; instead they are forced to grow at the root.

When inserting into a B-tree, a value is inserted directly into a leaf. This leads to three common situations
that can occur:
1. A key is placed into a leaf that still has room.
2. The leaf in which a key is to be placed is full.
3. The root of the B-tree is full.

CASE 1: A key is placed into a


leaf that still has room
This is the easiest of the cases to
solve because the value is simply
inserted into the correct sorted
position in the leaf node.

Inserting the number 7 results in:

CASE 2: The leaf in which a key is to be placed is full


In this case, the leaf node where the value should be inserted is split in two, resulting in a new leaf node.
Half of the keys will be moved from the full leaf to the new leaf. The new leaf is then incorporated into the
B-tree.

CMPE-30052 Page 76 of 90
The new leaf is incorporated by moving the middle value to the parent and a pointer to the new leaf is
also added to the parent. This process is continues up the tree until all of the values have "found" a
location.

Insert 6 into the following


B-tree:

Results in a split of the first


leaf node:

The new node needs to be incorporated into the tree - this is accomplished by taking the middle value
and inserting it in the parent:

CASE 3: The root of the B-tree is full


The upward movement of values from case 2 means that it's possible that a value could move up to the
root of the B-tree. If the root is full, the same basic process from case 2 will be applied and a new root
will be created. This type of split results in 2 new nodes being added to the B-tree.

CMPE-30052 Page 77 of 90
Inserting 13 into the following tree:

Results in:

The 15 needs to be moved to


the root node but it is full.
This means that the root
needs to be divided:

The 15 is inserted into the parent,


which means that it becomes the
new root node:

DELETING FROM A B-TREE


As usual, this is the hardest of the processes to apply. The deletion process will basically be a
reversal of the insertion process - rather than splitting nodes, it's possible that nodes will be merged so
that B-tree properties, namely the requirement that a node must be at least half full, can be maintained.

CMPE-30052 Page 78 of 90
There are two main cases to be considered: Deletion from a leaf and Deletion from a Non- Leaf

CASE 1: Deletion from a leaf


A. If the leaf is at least half full after deleting the desired value, the remaining larger values are
moved to "fill the gap".

Deleting 6 from the


following tree:

Results in:

B. If the leaf is less than half full after deleting the desired value (known as underflow), two things
could happen

Deleting 7
from the tree
above results in:

• If there is a left or right sibling with the number of keys exceeding the minimum
requirement, all of the keys from the leaf and sibling will be redistributed between them
by moving the separator key from the parent to the leaf and moving the middle key from
the node and the sibling combined to the parent.

CMPE-30052 Page 79 of 90
Now delete 8 from the tree:

• If the number of keys in the sibling does not exceed the minimum requirement, then the
leaf and sibling are merged by putting the keys from the leaf, the sibling, and the
separator from the parent into the leaf. The sibling node is discarded and the keys in the
parent are moved to "fill the gap". It's possible that this will cause the parent to
underflow. If that is the case, treat the parent as a leaf and continue repeating step 1b-2
until the minimum requirement is met or the root of the tree is reached.

Watch:
1. https://www.youtube.com/watch?v=qH6yxkw0u78

Read:
1. https://www.coelms.com
2. https://www.studytonight.com/data-structures/introduction-to-data-structures

Review:
1. https://www.studytonight.com/data-structures/introduction-to-data-structures

Activities/Assessments:

CMPE-30052 Page 80 of 90
LABORATORY EXERCISE 8
Complete the following code and then generate an equivalent code in python:

CMPE-30052 Page 81 of 90
CMPE-30052 Page 82 of 90
COEN30052 DATA STRUCTURE AND ALGORITHM ANALYSIS
FINAL EAMINATION
Name Date
Section Score

MULTIPLE CHOICE [100pts]. Choose AND ENCIRCLE the letter of the BEST answer.
1 Linked list are

a. dynamic data b. static data structure c. arrays d. pointers


structure
2 In simply queue existing elements are deleted from the other end called.

a. front b. bottom c. rear d. middle

3 Allows insertion at only one end (rear end) but allows deletion at both ends, rear and front ends
on the lists.
a. output restricted b. input restricted c. priority queue d. circular queue
queue queue
4 Place where insertion and deletion takes place in stack.

a. bottom b. rear c. top d. front

5 Queue elements where it is represented in a circular fashion way

a. deque b. double ended c. circular queue d. priority queue


queue
6 Pointer identifier in the linked list that points to the first node.

a. tail b. middle c. rear d. head

7 The data values in this structure are not arranged in order.

a. stack b. queue c. linear d. non-linear

8 Type of data structures, data values of different types are grouped and stored.

a. homogenous b. pointer c. linked list d. non-homogenous

9 Is a homogenous list in which elements can be added or inserted and deleted or removed from
both ends.
a. priority queue b. circular queue c. double ended d. dequeue
queue
10 In stack every pop operation, the top of the stack is.

a. doesn’t change b. incremented by 2 c. decremented by d. incremented by 1


1
11 Insert (or add) an element to the queue (push)

CMPE-30052 Page 83 of 90
a. enqueue b. dequeue c. pop d. traverse

12 In stack collection of data items can only be accessed at the

a. bottom b. top c. middle d. rear

13 Operators is written after the operands.

a. prefix b. postfix c. infix d. polish notation

14 Specially designed data elements in a linked list.

a. data b. next pointer c. nodes d. variable address

15 The deletion (or remove) stacks operation.

a. enqueue b. pop c. dequeue d. push

16 Is the operation of data and the operations allowed on that data.

a. structured b. primitive data types c. data structure d. object oriented

17 A notation where the Operator is written in-between the operands

a. prefix b. postfix c. infix d. suffix

18 In simply queue new elements are added at one end called

a. front b. rear c. middle d. top

19 In stack program the top of stack is initialized to a value

a. negative one (-1) b. positive one (1) c. zero (0) d. NULL value

20 Stack behavior

a. FIFO b. LIFO c. LILO d. FILO

21 Allows deletion at only one end (front end) but allows insertion at both ends, rear and front
ends, of the lists.
a. input restricted b. output restricted c. circular queue d. simply queue
queue
22 Process of going through all the nodes from one end to another end of the linked list.

a. searching b. traversing c. looping d. inserting

23 The process of inserting an element on one end and deleting an element on the other end

a. stack b. dequeue c. queue d. linked list

24 Type of data structure where values of the same types of data are stored.

CMPE-30052 Page 84 of 90
a. pointer b. linked list c. non- d. homogeneous
homogeneous
25 Queue behavior

a. FIFO b. LIFO c. LILO d. FILO

26 A condition occurs if the array is full and no new element can be accommodated.

a. overflow b. underflow c. full d. empty

27 Enables a program to move through the list in one direction, which is usually from the front of
the list moving to the end of the list.
a. doubly linked list b. singly linked list c. circular linked list d. doubly circular
linked list
28 A notation where the operators is written before the operands.

a. postfix b. prefix c. suffix d. infix


29 The insertion (or addition) stacks operation.

a. pop b. push c. top d. remove

30 Is a collection of items that exhibits the behavior that the last item in is the first item out.

a. queue b. stack c. linked list d. circular queue

31 Is a data structure that makes it easy to rearrange data without having to move data in
memory.
a. array b. stack array c. linked list d. queue array

32 Appending the second list to the end of the first list.

a. addition b. concatenation c. insertion d. deletion

33 Delete (or remove) an element from a queue (pop)


a. enqueue b. push c. dequeue d. insert

34 Enables the program to move through the list in both directions.

a. circular linked list b. singly linked list c. doubly linked list d. queue

35 Stores data and allow various operations on the data to access and change it.

a. data structure b. int data type c. primitive data d. abstract data type
type
Question number 36 to 40 convert the given expression to prefix form

36 A*C/D

CMPE-30052 Page 85 of 90
a. * / A C D b. / * A C D c. / C D * A d. * A / C D

37 A+B^C–D

a. – + A ^ B C D b. ^ – + A B C D c. + A B ^ – C D d. – + ^ A B C D

38 (A+B)*C/D

a. * + A B / C D b. / * + A B C D c. + A B * / C D d. * + / A B C D

39 (A*B)^C–D*F

a. – ^ * A B C * D F b. – * A ^ B C * D F c. * A B ^ – C * D F d. * ^ – A B C * D F

40 A+B–C*D/E^F

a. – + A B / * C D ^ E b. + A B – * C D / ^ E c. + A B – * C / D E d. + A B – / * C D ^ E
F F ^F F
Question number 41 to 45 convert the given expression to postfix form

41 A*B–C

a. A B * C – b. A B C * – c. A B C – * d. A B – C *

42 A+(B–C)^D

a. A B C – D + ^ b. A B C – + D ^ c. A B C – D ^ + d. A B C D + – ^

43 A^B–C/D

a. A B C D ^ – / b. A B C ^ – D / c. A B ^ C D / – d. A B ^ – C D /

44 A/(B*C)+D

a. A B C D / * + b. A B C * / D + c. A B / C * D + d. A B C / * D +

45 A^(B*C)/(D–F)

a. A B C D F ^ * / – b. A B C * ^ / D F – c. A B C * ^ D F / – d. A B C * ^ D F – /

46 It is the immediate predecessor of a node.

a. parent b. descendants c. child d. sibling

47 The highest number of nodes that is possible in a way starting from first node (ROOT) to a leaf.

a. height b. depth c. level d. path

48 Maximum level of any leaf of a tree

a. path b. height c. depth d. level

49 Is the rank of tree hierarchy.

CMPE-30052 Page 86 of 90
a. depth b. level c. path d. height

50 The node with degree zero.

a. sub tree b. root c. parent d. terminal

51 In Binary tree, any node that has at least one empty child

a. external node b. leaf c. internal node d. root node

52 Stores keys in the nodes in a way so that searching, insertion and deletion can be done
efficiently.
a. struct b. tree data structure c. binary search d. heap
tree
53 It is the mother node of a tree structure.

a. root b. sibling c. leaves d. parent

54 It is called the child node of the same parent.

a. ancestors b. sibling c. descendants d. parent

55 A data structure that is ideal in representing hierarchical data.

a. tree b. stack c. organizational d. queue


chart
56 Is the number of successive edges from source node to destination node.

a. edge b. link c. path length d. height

57 All successor of the parent node are called ________ nodes.

a. parent b. root c. child d. sibling

58 The maximum number of children that exists for a node.

a. degree of a node b. zero c. root node d. depth


59 A tree is binary if each node of it has a maximum of ______ branches.

a. zero b. two c. one d. three


60 A type of binary tree in which each level of the tree is completely filled.

a. complete b. restrict c. strict d. incomplete

61 It is the line drawn from one node to other node in a tree.

a. flow lines b. height c. Link or Edge d. path

62 It is the simplest form of a tree.

a. array b. binary tree c. linked list d. linked list

CMPE-30052 Page 87 of 90
63 A type of binary tree where every non-leaf node is filled with left and right sub-trees

a. complete b. incomplete c. strictly binary tree d. complex

64 This node is located at the end of the tree.

a. Leaf b. root c. parent d. level 5

65 It is a group of disjoint trees.

a. subtree b. forest c. binary tree d. root tree

66 A sort algorithm where each element is compared with its adjacent element. If the first element
is larger than the second one, then the positions of the elements are interchanged, otherwise it
is not changed
a. quick sort b. bubble sort c. heap sort d. selection sort

67 A sort algorithm that finds the smallest element of the array and interchanges it with the
element in the first position of the array. Then it finds the second smallest element from the
remaining elements in the array and places it in the second position of the array and so on.
a. selection sort b. quick sort c. bubble sort d. insertion sort

68 Sorting algorithm that sorts a set of values by inserting values into an existing sorted file.

a. selection sort b. quick sort c. bubble sort d. insertion sort

69 Is the process of combining two or more sorted array into a third sorted array.

a. merging b. selecting c. inserting d. sorting

70 A sorting algorithm that is defined as an almost complete binary tree of n nodes such that the
value of each node is less than or equal to the value of the father.
a. insertion b. selection c. heap d. quick

71 In Binary Search Tree a key value in the left child is more than the value of _____.

a. parent b. ancestor c. sibling d. root


72 The node of a tree stores the data and its role is the same as in the ___________.

a. array b. linked list c. primitive data d. stack


types
73 It connects the two nodes in a tree.

a. line b. leaf c. edge d. path

74 The level of the root node is always at level _____.

a. level 0 b. level 1 c. level 2 d. depth

75 In expression trees, __________ are operands (constant or variables)

CMPE-30052 Page 88 of 90
a. node b. internal node c. root d. leaf

76 In Binary Search Tree a key value in the right child is ____________to the value of root.

a. more than only b. equal c. more than or d. less than


identical
77 A root does not have a _______

a. sibling b. descendant c. parent d. none of the above

78 Each data item in a tree is called a _____.

a. root b. node c. parent d. leaf

79 Refers to the process of visiting each node in a tree data structure, exactly once, in a
systematic way
a. searching b. sorting c. merging d. tree traversal

80 Is a link field and holds the address of its left node.

a. left child b. right child c. sibling d. parent

81 Binary tree operation to create an empty binary tree.

a. isEmpty b. create c. parent d. search

82 Sequence for inorder traversing

a.left-right-root b. left-root-right c .root-left-right d. right-left-root

83 Sequence for postorder traversing

a. root-left-right b. left-root-right c. left-right-root d. root-right-left

84 Occurs when a function is called by itself repeatedly.

a. Repetition b. Recursion c. Condition d. Iteration

For number 85 to 90 refer to figure A.

Figure A

CMPE-30052 Page 89 of 90
85 Parent of e

a. d only b. c only c. g only d. f only

86 Sibling of k.

a. i b. e c. a d. none

87 descendants of c

a. a and e b. g only c. a, b, d, e, and f d. j only

88 Who are the leaf nodes

a. b, d, f, h and l b. a, c, e, g, i, j, and k c. b and k d. b, d, f, h , l, and k

89 level of e

a. level 0 b. level 1 c. level 2 d. level 3

90 descendants of j

a. g only b. h, i, l, and k c. i and k d. c

For number 91 to 100 Given the following value 18, 15, 30, 17, 35, 10, 22, 13, 18, 16, 31, 8, 25, 9, 4
91-94: Draw the equivalent Binary Search Tree
95-96: Write the values using the in order traversal
97-98: Write the values using the pre order traversal
99-100: Write the values using the post order traversal

Answer for 91-94

CMPE-30052 Page 90 of 90

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