Unit 1 Data Structures Introduction
Unit 1 Data Structures Introduction
Syllabus
SUBJECT CODE SUBJECT TITLE CORE/ ELECTIVE CREDITS
L T P C
CSE 102 Data Structures C 3 0 2 4
NOTE: The syllabus given herein shall be followed and further additions/deletions are possible
based on the time factor.
Unit I
• Introduction to data structures, Abstract Data Type (ADT) representation and
implementation of ADT, time and space requirements of algorithms.
• Array ADT, representing polynomials, sparse matrices using arrays and their operations.
• Stacks and Queues: Representation and application, implementation of stack and queue
operations.
Unit - II
• Linked lists: Single linked lists, implementation of link list and various operation, Double linked
list and circular list.
Dept. of CSE, SRM University AP 8/3/2021 2
Syllabus
UNIT – III
Trees: Tree terminology, Binary tree, Binary search tree, Complete Binary Tree
representation, infix to post fix conversion, postfix expression evaluation. General tree, AVL
Tree.
UNIT – IV
Graphs: Graph terminology, Representation of graphs, Path matrix, BFS (breadth first search),
DFS (depth first search), topological sorting, Shortest path algorithms
UNIT – V
2) “Data structure using C”, Aaron M. Tenenbaum, Y Langsam and Mosche J. Augenstein, Pearson
publication.
Books of References
1. “Fundamentals of data structure in C” Horowitz, Sahani & Anderson Freed, Computer Science
Press.
2. “Data Structures Using C”, Reema Thareja, Oxford Higher Education, 2nd edition.
4. “Data Structures & Algorithms; Concepts, Techniques & Algorithms”, G. A. V. Pai, TMG Hill.
Dept. of CSE, SRM University AP 8/3/2021 4
Course Outcomes
The lavender colored words are the actions verbs that are carefully chosen from Blooms
Taxonomy which indicate the knowledge, skill set and attuite/behaviors students gain at the
end of the course.
Distribution of Marks
Legends
Symbol Description
Announcements
Notes
Group activity
Reading Material
Lecture Session
Quiz time
Prerequisites for the course
▪ Data Types
▪ Data Structures
▪ Abstract Data Types (ADT)
▪ Why ADTs?
▪ Definition of Algorithm
Definition of Structures
Dictionary meaning of Structure:
▪ The arrangement of and relations between the parts or elements of
something complex.
Or
▪ The way in which the parts of a system or objects are arranged or
organized.
▪ Examples:
▪ The grammatical structure of a sentence.
▪ The structure of this protein is particularly complex.
▪ They have a very new-fashioned management structure.
▪ This institute has a different administration structure.
▪ Many temples in India have a pyramid structures.
Things to ponder …
Consider an example
Scenario (example-1)
Scenario (example-2)
Getting to the topic
▪ (The meaning insights that are obtained form these conclusion, after
statistical analysis, is called as Information).
Or
▪ Data (singular datum) are individual units of information. A datum
describes a single quality or quantity of some object or phenomenon.
Or
▪ Raw observations made by an entity(Human or Machine) about an
event/Phenomenon either continuously or at particular intervals.
Definition of Data
Examples:
▪ Now the data is/are being transferred from magnetic tape to hard
disk.
▪ Scientists hope that data from the space probe will pave the way
for a more detailed exploration of Mars.
▪ The system will handle phone calls and data messages as well as
other signals that need high bandwidth.
Example of Data
Examples of Data
[Link]
Example of Data
Examples of Data
Example of Data
• What to do with this data?
Data
… and putting them together we have Data Structures.
▪ So far we have seen the definition of structure(s) and Datum (data).
▪ We also have observed that arrangement or organization of elements or
entities are a matter of concern, in terms of:
▪ Space
▪ Time
▪ Let’s now see “why arrangement or organization of data using structures
matter?”
▪ Here we go…
▪ What observation have you made?
▪ In terms of Space? Time was reduced in each case of the algorithm
▪ In terms of Time?
Size of the array (space) is fixed
What motivates you to continue with this course?
▪ Arrays
▪ Stacks
▪ Queues
▪ Linked Lists
▪ Adjacency Lists
▪ Adjacency Matrices
▪ Trees
▪ Graphs
Tree
Structure Ring
Structure
Wondered why the tree is shown inverted?
I will tell you the reason when I teach TREE Data Structure
Opps…I am sorry
We have a tree that is upside down. So I was correct.s
[Link]
Now about the course Data Structures
… and putting them together we have Data Structures
▪ The course Data Structures deals wit the study of methods, techniques and
tools to organize or structure data.
▪ It deals with the study of “how the data is organized in memory, how
effectively it can be stored, retrieved and manipulated.”
▪ It deals with the design and implementation of efficient algorithms.
▪ Key terms:
▪ Data
▪ Structures
▪ Tools
▪ Algorithm(s)
▪ Efficient – time and space complexity
Definition of Data Structures
Data Structure
▪ Is an aggregation of atomic data and composite data into a set with defined
relationships.
9 9 7 3 1 2 7 9 0 6
▪ A Data Type consists of two parts: a set of data and the operations that can
be performed on the data.
Set of operations
Set of data
+, -, *, /, %, ++, --, bit wise
. . ., -2, -1, 0, 1, 2, . . .
operator. . .
Set of operations
Set of data +, -, *, /
. . ., -2.0, -1.0, 0.0, 1.0, 2.0, . . . But bit-wise and % operation are
not permitted
Atomic Data
Data Structure Composite Data
Defined relationships
Data Structures A Pseudocode Approach with C by Richard F. Gilberg & Behrouz A. Forouzan
Non-primitive Data Types
▪ User defined data types are known as non-primitive data types, which are derived
from or obtained by combining primitive data types.
▪ Specifically, the set of values and the operations necessary to perform on those
set of values are defined by the user (the programmer, you), not the program
itself.
▪ Examples:
1. Structures – obtained by combining different data types such as int, char, float.
▪ E.g. Struct Student {
char Name;
int Roll_No;
float CGPA;
};
2. Unions
3. Enumeration
Abstract Data Type
• A protype or a blueprint or a template.
• These are similar to non-primitive (user defined) data types that define operations on
values using FUNCTIONS without specifying the actual implementation details of the
FUNCTIONS and without mentioning how the operations are performed by the
FUNCTIONS. However, you are told what are the operation (names of the operations)
that are available to you.
• Example:
• Do you know how you laptop (or PC) reads the data from the keyboard?
• Specifically, do you know the code to read the keyboard?
• The keyboard ADT has
• A Data Structure = Set of characters + set of operations that that can be used to read that
data structure.
• Do you have this question in your mind?
• “The keyboard has characters, integers, special symbols, floating point number (of course you
enter them form KB) which are different data types, then how can we perform operations on
data types of different type?”
Abstract Data Type
• Excellent, you are on the track
• Using ADT we can convert one type of data structure to different data
structure such as integer and strings.
• The program which uses data structures is called the client program, it has
access to the ADT i.e, the interface.
• The program which implements the data structures is known as the
implementation.
Types of Data
Structures
Primitive DS Liner DS
Non Primitive DS Non-linear DS
Other operations
▪ Traversing – accessing each data element exactly once so that certain item in
data structure may be processed.
▪ Do the following:
▪ Analyse the problem
▪ Determine the basic operations
▪ Select the DS that best meets our needs
Recap
Recap
We have earlier studied the following linear data structures such as:
▪ Arrays
▪ Stacks
▪ Linked Lists
▪ Queues
49
STACKS
In computer world : In
processing of subroutine
calls and returns ; there is
an explicit use of stack of
return addresses.
Also in evaluation of
arithmetic expressions ,
stack is used.
STACKS Operations
Primary operations defined on a stack:
▪ Also "IsEmpty()" and IsFull()" function, which tests whether a stack is empty
or full respectively.
▪ Using Arrays
top 52
STACK Implementation Using Array
Peek() is one of a stack operation that prints the value of the top most
element of the stack without deleting that element from the stack.
The next two slides have the complete C code for Stack operations
STACK Implementation Using Array
#include<stdio.h>
#define SIZE 10
void push(int);
void pop();
void display();
Void peek();
int stack[SIZE], top = -1;
void main()
{
int value, choice;
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Push\n 2. Pop\n 3. Peek\n [Link] \n 5. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
58
STACK Implementation Using Array
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;
case 3: peek();
break;
case 4: display();
break;
case 5: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}
}
}
STACK Implementation Using Array
void push(int value){
if(top == SIZE-1)
printf("\nStack is Full!!! Insertion is not possible!!!");
else{
top++;
stack[top] = value;
printf("\nInsertion success!!!");
}
}
void pop(){
if(top == -1)
printf("\nStack is Empty!!! Deletion is not possible!!!");
else{
printf("\nDeleted : %d", stack[top]);
top--;
}
} 60
STACK Implementation Using Array
void peek(){
if(top == -1)
printf("\nStack is Empty!!!");
else{
int i;
printf("\nStack top most element is: %d\n“,stack[top]);
}}
void display(){
if(top == -1)
printf("\nStack is Empty!!!");
else{
int i;
printf("\nStack elements are:\n");
for(i=top; i>=0; i--)
printf("%d\n",stack[i]);
}} 61
void push(int value){
#include<stdio.h>
if(top == SIZE-1)
#define SIZE 10
printf("\nStack is Full!!! Insertion is not possible!!!");
void push(int);
else{
void pop();
top++;
void display();
stack[top] = value;
void peek();
printf("\nInsertion success!!!");
int stack[SIZE], top = -1;
}}
void main()
{
void pop(){
int value, choice;
if(top == -1)
while(1){
printf("\nStack is Empty!!! Deletion is not possible!!!");
printf("\n\n***** MENU *****\n");
else{
printf("1. Push\n 2. Pop\n 3. Peek\n [Link] \n 5. Exit");
printf("\nDeleted : %d", stack[top]);
printf("\nEnter your choice: ");
top--;
scanf("%d",&choice);
}}
switch(choice){
case 1: printf("Enter the value to be insert: ");
void peek(){
scanf("%d",&value);
if(top == -1)
push(value);
printf("\nStack is Empty!!!");
break;
else{
case 2: pop();
int i;
break;
printf("\nStack top most element is: %d\n",stack[top]);
case 3: peek();
}}
break;
case 4: display();
void display(){
break;
if(top == -1)
case 5: exit(0);
printf("\nStack is Empty!!!");
default: printf("\nWrong selection!!! Try again!!!");
else{
}
int i;
}
printf("\nStack elements are:\n");
}
for(i=top; i>=0; i--)
printf("%d\n",stack[i]);
}}
STACK Implementation Using Array
▪ Application of stack in REVERSING a string.
Data Structures A Pseudocode Approach with C by Richard F. Gilberg & Behrouz A. Forouzan, 2 nd Edition, Cengage Learning
STACK Implementation Using Linked List
8. To check that every right brace, bracket, and parentheses must correspond to
its left counterpart e.g. [( )] is legal, but [( ] ) is illegal. To determine such
problem we use parenthesis.
Application Of Stack
2. Converting an infix expression to postfix expression:
Application Of Stack
Operators Precedence
(, {, [ ], }, ) 7
-, +, NOT (Binary) 6
^ (exponentiation) 6
*, / 5
+, - (Arithmetic) 4
<, >, <=, !=, >= 3
AND 2
OR, XOR 1
Application Of Stack
Infix to Postfix using stack (competitive exam stye)
Given: (A+B)/(C-D)
Given: (A + B) *C
Step 1: (E1) * (E2), where E1 = AB+
Step 1: (E) * C, where E = AB+
and E2 = CD-
Step 2: EC *
Step 2: E1 E2 /
Step 3: Replace E. i.e., we have AB+C*
Step 3: Replace E1 E2 . i.e., we have
AB+CD-/
Example : Conversion of infix expression to postfix
73
For detailed explanation refer to class video recordings
Application Of Stack
Infix to Postfix using stack (manual method)
▪ The examples you did so far, on Stack, used several stack operations – namely,
PUSH, POP, PEEK, CREATE_STACK, PRINT_STACK etc.
▪ While we could write them each time we needed them, this would certainly be an
inefficient use of our time.
▪ In earlier lab we have seen how the STACK defined to reverse a set of
characters was not working if the inputs were a set of integers.
▪ Because, the data type of characters is different for that of integers and we
had to modify the program to suit our needs.
.
Stack ADT (Abstract Data Type)
▪ Therefore, we need a way to overcome this issue and save our time.
▪ In our case, we need, therefore, a stack abstract data type that we can put in a
library and call whenever we need it.
▪ Rather than store data in each node, we store a pointer to the data.
▪ It is the application program’s responsibility to allocate memory for the data
and pass the address to the stack ADT.
▪ Within the ADT, the stack node looks like any linked list node except that it
contains a pointer to the data rather than the actual data.
▪ The head node and the data nodes are encapsulated in the ADT. The calling
function’s only view of the stack is a pointer to the stack structure in the ADT,
which is declared as a type definition.
Stack ADT (Abstract Data Type)
… The stack data structure:
Class Activity:
Given expression: Try this now.
- * 3 + 16 2 1 12 6
Ans: 52
88
Array ADT
▪ If you recall the information related to Arrays from your earlier semester,
then let’s consider few aspects related to Arrays.
▪ How many elements to store in that ARRAY – the size of the array.
▪ Information about the index that is pointing to the last element in the
array – call it LastIndex.
Offset
Size 10 0 1 2 3 4 5 6 7 8 9
LastIndex 6 12 17 4 5 22 28 79
ArrPtr 200 200 201 202 203 204 205 206 207 208 209
Addresses
Array ADT
▪ Value = 10
▪ Loc or index = 8, 5, 7, 14, 9, -1
▪ Case1: If index is < 0 or > Size is true, then print “Invalid index, please
enter the valid loc or index.”
▪ Case2: If index == LastIndex+1 is true, ArrPtr[LastIndex+1]=value.
▪ Case3: If LastIndex+1 == Size, then print array is full
▪ Case4: If index < LastIndex, then move the elements towards right
until the index of interest is free.
▪ Save the LastIndex address in i. that is I = 7
▪ Case5: If index >= LastIndex+2
Offset
Size 10 0 1 2 3 4 5 6 7 8 9
LastIndex 6/7 12 17 4 5 22 28 79
ArrPtr 200 200 201 202 203 204 205 206 207 208 209
Addresses
Array ADT
▪ Operations on Array Offset
0 1 2 3 4 5 6 7 8 9
▪ CreateArray
12 17 4 5 22 28 79
200 201 202 203 204 205 206 207 208 209
Addresses
▪ RetreiveItem RetreiveItem(3);
// Here 3 is the index of the element that we want to retreiive
StoreItem(3);
▪ StoreItem
// Here 3 is the index of the element that we want to retreiive
LastIndex 6
ArryPtr 200
▪ CreateArray()
▪ Polynomial Expression
▪ Sparse Matrix
5) Validation.
Something Interesting…
1. 1 circle
2. 120 points on circle(circumference)
3. 1000 lines (chords)
4. 3 hours work
Video
Pic1
Pic2
Pic3
Algorithm Analysis
Example :
1. PRACTICAL EXAMPLE : A line at a ticket counter for buying tickets operates on
above rules.
Remove Insert
(Dequeue) front rear (Enqueue)
100
Queue Operations
• There are several different algorithms to implement Enqueue and Dequeue
• When enqueuing, the front index is always fixed and the rear index moves forward
in the array.
rear rear rear rear rear
3 3 6 3 6 9 6 9 9
rear = -1
front=-1
Queue Implementation
102
Queue Implementation Using Array
Insert ( ): or EnQueue():
Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear of the QUEUE. ITEM is
the value to be inserted.
void deQueue(){
if(front == rear)
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else{
printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1;
}
}
#include<stdio.h> void enQueue(int value){
#define SIZE 10 if(rear == SIZE-1)
void enQueue(int); printf("\nQueue is Full!!! Insertion is not possible!!!");
void deQueue(); else{
void display(); if(front == -1)
int queue[10], front = -1, rear = -1; front = 0;
rear++;
void main() {
queue[rear] = value;
int value, choice;
printf("\nInsertion success!!!");
while(1){ }}
printf("\n\n***** MENU *****\n"); void deQueue(){
printf("1. Insertion\n2. Deletion\n3. Display\n4. Exit"); if(front == rear)
printf("\nEnter your choice: "); printf("\nQueue is Empty!!! Deletion is not possible!!!");
scanf("%d",&choice); else{
switch(choice){ printf("\nDeleted : %d", queue[front]);
case 1: printf("Enter the value to be insert: "); front++;
scanf("%d",&value); if(front == rear)
enQueue(value); front = rear = -1;
break; }}
case 2: deQueue(); void display(){
break; if(rear == -1)
case 3: display(); printf("\nQueue is Empty!!!");
break; else{
int i;
case 4: exit(0);
printf("\nQueue elements are:\n");
default: printf("\nWrong selection!!! Try again!!!");
for(i=front; i<=rear; i++)
} printf("%d\t",queue[i]); 105
}} }}
Trees Basics
▪ Data will be represented in multiple levels
106
Natural View of a Tree
Leaves
Branches
Root
107
Computer Scientist’s View of a Tree
Root Leaves
Branches Father & Mother
Branches
Child
Child
Root
Grand Children
Grand Children
Intermediate nodes or
108
Leaves inner nodes
Types of Trees
Some of the popular tree types are: Operation on Trees
▪ Root-node: A node without parent (A) OR in a nonempty tree, the first node is
called the root.
▪ Siblings-nodes share the same parent. Nodes D & E are siblings; nodes F and G
are siblings & nodes I & J are siblings.
▪ Internal node: Node with at least one child (A, B, C, D,F). Other way is all
non-leaf nodes are internal nodes
[Link]
Tree Terminology
▪ Level: The level of a node is its distance from the root node.
▪ Level of a root is 0.
▪ Children of a root are at level 1.
▪ Their children are at level 2 and so on.
Tree Terminology
Root A Level 0
The dashed
B is the parent
line is the path
of D and E
B E is the right C Level 1
D is the left
child of B child of B
D E
F G Level 2
▪ Represented as InDeg(node_ID).
A
▪ E.g., InDeg(A) = 0
B D
▪ InDeg(B) = InDeg(C) = InDeg(D) = 1 C
▪ NOTE: The sum of the indegree and outdegree branches of a node is the
degree of the node.
Tree Terminology
B D
C
E H G
F
Limitations of BST
log2(n)
▪ The minimum height of a BST _______
▪ Want to confirm?
▪ The size of the input remains same (= 7 nodes) in both the cases.
▪ In AVL tree, the heights of the two sub-trees of a node may differ by at most
one.
▪ Due to this property, the AVL tree is also known as a height-balanced tree.
▪ Advantage: Insert and Delete operations take, on average, take O(log (n)) time.
▪ The structure of an AVL tree is same as that of a BST but with an extra
information – BalanceFactor (or depth difference)
▪ Balance Factor (BF) = HLST – HRST; where HLST and HRST are height of left
sub-tree and right sub-tree respectively.
AVL Trees
0 0 0
1
27 39 54 72
18
0
AVL Trees
45 45
36 63 63
36
27 54 72 54
39 27 39 72
BF of Node 27 = 0 0
70 BF of Node 27 =
BF of Node 39 = 0 0
BF of Node 39 =
BF of Node 36 = 0 0
BF of Node 36 =
BF of Node 54 = 0 0
BF of Node 54 =
BF of Node 70 = 0 0
BF of Node 72 =
BF of Node 72 = 1 0
BF of Node 63 =
BF of Node 63 = -1 0
BF of Node 45 =
BF of Node 45 = -1
AVL Trees
▪ Insertions and deletions may disturb the balance of a tree.
▪ So what to do?
▪ Rebalancing is necessary.
▪ The only nodes whose balance factors will change are those which lie in the path
between the root of the tree and the newly inserted node.
▪ The possible changes which may take place in any node on the path are as
follows:
▪ Initially, the node was either left- or right-heavy and after insertion, it
becomes balanced.
▪ Initially, the node was balanced and after insertion, it becomes either left-
or right-heavy.
▪ Initially, the node was heavy (either left or right) and the new node has
been inserted in the heavy sub-tree, thereby creating an unbalanced
sub-tree. Such a node is said to be a critical node.
AVL Trees
45 -1 45 0
36 0 63 -1 36 1 63 -1
27 0 54 0 72 1 0 54 0 1
39 0 27 -1 39 72
70 0 70 0
30 0
Insert 30
▪ Initially, the node was either left- or right-heavy and after insertion, it
becomes balanced.
AVL Trees
45 -1
45 0
36 0 63 -1
36 0 63 0
54 0 1
27 0 54 0 72 0 27 0 39 0 72
39 0
71 0
Insert 71
▪ Initially, the node was balanced and after insertion, it becomes either
left- or right-heavy.
AVL Trees
45 0 45 1
36 2 63 -1
36 1 63 -1
0 54 0
27 -2 39 72
0 54 0 1 1
27 -1 39 72
70 0
70 0 30 1
30 0
Insert 29
029
▪ Initially, the node was heavy (either left or right) and the new node has been
inserted in the heavy sub-tree, thereby creating an unbalanced sub-tree.
▪ Such a node is said to be a critical node.
AVL Trees
▪ Is the tree imbalanced after you inserted a 45 -2
new node?
▪ If yes, then follow the mentioned steps. 36 0 63 -2
▪ LL rotation The new node is inserted in the left sub-tree of the left
sub-tree of the critical node.
▪ RR rotation The new node is inserted in the right sub-tree of the right
sub-tree of the critical node.
▪ LR rotation The new node is inserted in the right sub-tree of the left
sub-tree of the critical node.
▪ RL rotation The new node is inserted in the left sub-tree of the right
sub-tree of the
AVL Trees
For three nodes having the values 27, 36 and 45. The red node is the critical
node (CN)
There could be the following choices of trees based on the input sequence.
45 45 27
27 36
36
27 45 36
27 45
27
36 36 45
Which is the best one and why?
Then can we change the first four into the form that looks like the fifth one?
AVL Trees - Insertion
1. LL rotation The new node is inserted in the left sub-tree of
the left sub-tree of the critical node.
45
• Given the nodes of a tree. BF = 2
• No. Then …?
• Perform LL rotation.
AVL Trees - Insertion
1. LL rotation The new node is inserted in the left sub-tree of
the left sub-tree of the critical node.
BF = 0 27 45
BF = 0
AVL Trees - Insertion
2. RR rotation The new node is inserted in the right sub-tree
of the right sub-tree of the critical node.
27 BF = -2
• Given the nodes of a tree.
• Insert 45.
36 BF = -1
• How does your tree look like?
• No. Then …?
• Perform RR rotation.
AVL Trees - Insertion
2. RR rotation The new node is inserted in the right sub-tree
of the right sub-tree of the critical node.
• Insert 36.
27 BF = -1
• How does your tree look like?
• Perform LR rotation.
AVL Trees - Insertion
3. LR rotation The new node is inserted in the right sub-tree of
the left sub-tree of the critical node.
Step-1: Step-2:
BF = 2 • From newly BF = 2 • Now apply LL 36
45 inserted node transformation
45
(say 36) go one
step back • That is
perform right 27 45
towards root
27 BF = -1 36
(say 27). rotation
BF = 1 keeping middle
• Now perform 27 node as new
rotate left root.
36 BF = 0
considering
BF = 0 both the nodes
together (36
and 27)
AVL Trees - Insertion
4. RL rotation The new node is inserted in the left sub-tree of
the right sub-tree of the critical node (here it is 27)
• Is it balanced?
36 BF = 0
• No. Then …?
• Perform RL rotation.
AVL Trees - Insertion
4. RL rotation The new node is inserted in the left sub-tree of
the right sub-tree of the
Step-1: BF = -2
• From newly Step-2: 36
BF = -2 inserted node 27 • Now apply RR
27
(say 36) go one transformation
step back BF = -1
towards root • That is 27 45
36
45 BF = 1 (say 45). perform left
rotation
• Now perform 45 keeping middle
rotate right node as new
36 BF = 0 considering BF = 0 root.
both the nodes
together (36
and 45)
AVL Trees - Deletion
▪ Deletion in ALV tree follows the same rules as the deletion in BST.
▪ However, this time the balance of the AVL tree is checked. If it is imbalanced
the rebalancing is necessary
▪ Deletion cases:
1. Case1: If the node to be deleted has no children, i.e., it is a leaf node, then
you are done.
2. Case2: If the node to be deleted has either left or right sub-tree (LST or
RST), then link that ST with the parent of the deleted node.
3. Case3: If the node to be deleted has both sub-trees then replace the
position of the deleted node with
a. either the largest node of LST
b. or smallest node of the RST
AVL Trees - Deletion
▪ Once the deletion and linking is done, update the BFs.
▪ If the tree is imbalanced, then do rebalancing.
▪ Rebalancing cases:
1. R0 -> LL rotation 4. L0 -> RR rotation
2. R+1 -> LL rotation 5. L+1 -> RL rotation
3. R-1 -> LR rotation 6. L-1 -> RR rotation
▪ How to interpret those 6 cases?
▪ Steps:
▪ After updating the BFs, find the critical node (CN).
▪ Now determine the BF of the left child, for instance, of CN. Let us say its
BF = -1
▪ Suppose the deleted node, for instance, is to the right of the CN ,then
choose L (for left)
▪ Now put together, read it as L-1 case. Implies RR rotation must be peformed.
AVL Trees - Deletion
Examples:
In the given AVL tree, delete the following nodes: 52, 36 and 61.
+1
55
0
+1
45
0 63
0
36 51
0
0 0 0 0 61
18 39 47 52
AVL Trees - Deletion
Since 52 has no children, we just need to update the BF and determine the BF.
+1 +1
55 55
0 0
+1 +1
45 45
0 0 63
0 63 +1
36 36 51
51 0
0 0 0 61
0 0 0 0 61 0
18 18 39
39 47 47
52
▪ Node 52 has no children, so we just need to update the BF and determine the
balancing criteria.
▪ The updated BFs indicate that the tree is balanced and no rebalancing in
necessary.
AVL Trees - Deletion
Delete 36:
Since 36 has two children, its position can be replaced by either largest node in
LST or smallest node in RST.
Let us choose largest node in LST
+1 +1
55 55
0 0
+1 +1
45 45
0 63 -1 63
0 +1
18
36 51 51
0 0
0 0 0 61 0 0 61
18 39 39 47
47
▪ The updated BFs indicate that the tree is balanced and no rebalancing in
necessary.
AVL Trees - Deletion
Delete 61: +1 +2
55 55
0 0
+1 0
45 45
-1 63 -1
+1 +1 63
18 18
51 51
0
0 0 61 0 0
39 47 39 47
▪ After updating the BFs, we find that node 55 becomes the CN.
▪ Now check for the rule patterns as follows:
1. Node deleted was on to the right of CN, so it is R.
2. The child of CN has BF = 0 (i.e., node 45’s BF is 0), so the combination is R 0.
3. So perform LL rotation.
Note: For rotations we need 3 nodes. Starting from node CN and downwards
towards the leaf, choose 3 nodes that are in RR pattern.
AVL Trees - Deletion
After rotations the tree is as shown below with BF updated.
-1
45
18 -1 55 +1
0 39 51 +1 63 0
47 0
AVL Trees
▪ We know that a BST of height h can support any of the basic dynamic-set
operations – such as SEARCH, PREDECESSOR, SUCCESSOR, MINIMUM,
MAXIMUM, INSERT, DELETE – in O(h) times., where h = n.
▪ We have seen how AVL trees can perform better on these operation with
worst-case time complexity of O(log2(n)).
▪ In this session, we shall study another such height balancing trees known
as RED-BLACK Trees.
Red-Black Trees
History:
▪ In 1972, Rudolf Bayer invented a data structure that was a special order-4
case of a B-tree.
▪ These trees maintained all paths from root to leaf with the same number
of nodes, creating perfectly balanced trees.
▪ However, they were not binary search trees. Bayer called them a
"symmetric binary B-tree" in his paper [1] and later they became popular as
2-3-4 trees or just 2-4 trees.
▪ In a 1978 paper, "A Dichromatic Framework for Balanced Trees", [2] the
authors derived the red-black tree from the symmetric binary B-tree.
▪ The color "red" was chosen because it was the best-looking color produced
by the color laser printer available to the authors while working at Xerox
PARC. Another response from Guibas states that it was because of the red
and black pens available to them to draw the trees.
[1] Rudolf Bayer (1972). "Symmetric binary B-Trees: Data structure and maintenance algorithms". Acta Informatica. 1 (4): 290–306.
[2] Leonidas J. Guibas and Robert Sedgewick (1978). "A Dichromatic Framework for Balanced Trees". Proceedings of the 19th Annual
Symposium on Foundations of Computer Science. pp. 8–21
Red-Black Trees
▪ A red-black tree is a BST with one extra bit of storage per node: its color,
which can be either RED or Black.
▪ If a child or the parent of a node does not exist, the corresponding pointer
attribute of the node contains the value NIL.
▪ By constraining the node colors on any simple path from the root to a leaf,
red-black trees ensure that no such path is more than twice as long as any
other, so that the tree is approximately balanced.
Red-black Trees
NOTE: We shall regard these NILs as being pointers to leaves (external nodes)
of the binary search tree and the normal, key-bearing nodes as being internal
nodes of the tree.
NIL or NULL is important to know the 5th property else it is most of the time
skipped.
Red Black Trees
Cases:
▪ Case-1: If the tree is empty, create a new node as the root node and color it
black (by default the new node inserted is always RED). Else call case-2
▪ Case-2: If the tree is not empty, create a new node as the leaf node and color
it RED. If the new node’s parent is BLACK then exit. Else call case-3.
▪ Case-3: If the parent of new node if RED, then check the color of parent’s
sibling (uncle’s color):
▪ Sub-Case-3a: If uncle’s color is RED, then recolor both parent’s and uncle’s
colors. Then check the color of grandparent. Recolor grandparent’s color if
it is not the ROOT node and recheck recursively until done.
▪ Sub-Case-3b: If uncle’s color is BLACK or if it is NUL then do appropriate
rotations and then recolor accordingly (swap the colors of --- and uncle
after rotation).
Examples: See handwritten notes
Deletion in RED-Black Trees
Cases:
▪ Case-1: If the node to be deleted is a RED leaf node, then just delete it. Assign
its parent a BLACK NIL node.
▪ Case-2: If a node to be deleted has 2 non-NIL children, then replace the node
with its in-order successor and delete the successor node.
▪ Case-3: If node to be deleted is BLACK but has one RED child then replace it
with that child’s value and change the color of the child to BLACK
▪ Case-4: If the node to be deleted is BLACK and has two BLACK children, then
this is a double-black situations and this has SIX (6) subcases.
Deletion in RED-Black Trees
Sub-Cases:
▪ Case-4a:
Root
▪ In a splay tree, operations such as insertion, search, and deletion are combined
with one basic operation called splaying.
▪ Splaying the tree for a particular node rearranges the tree to place that node
at the root.
▪ We shall discuss the four main operations that are performed on a splay tree.
Splaying
▪ When we access a node N, splaying is performed on N to move it to the root.
▪ To perform a splay operation, certain splay steps are performed where each
step moves N closer to the root.
▪ Splaying a particular node of interest after every access ensures that the
recently accessed nodes are kept closer to the root and the tree remains
roughly balanced, so that the desired amortized time bounds can be achieved.
Splay Trees
▪ Depending on these three factors, we have one splay step based on each factor.
Splay Trees
P N
N P
T3 T1
T1 T2
T2 T3
Zig Step:
▪ The zig operation is done when P (the parent of N) is the root of the splay
tree.
▪ In the zig step, the tree is rotated on the edge between N and P.
▪ Zig step is usually performed as the last step in a splay operation and only
when N has an odd depth at the beginning of the operation.
Splay Trees
P N
G
P G
T4 N P
T1
N
T3 T1 T2 T3 T4 G
T2
T1 T2
T3 T4
Zig-Zig Step:
▪ The zig–zig operation is performed when P is not the root.
▪ In addition to this, N and P are either both right or left children of their
parents.
▪ Figure shows the case where N and P are the left children.
▪ During the zig–zig step, first the tree is rotated on the edge joining P and its
parent G, and then again rotated on the edge joining N and P.
Splay Trees
G G N
P
T4 P G
N T4
T1 N
P T1 T2 T3 T4
T3
T2 T3
T1 T2
Zig-Zag Step:
▪ The zig–zag operation is performed when P is not the root.
▪ In addition to this, N is the right child of P and P is the left child of G or
vice versa.
▪ In zig–zag step, the tree is first rotated on the edge between N and P,
and then rotated on the edge between N and G.
Splay Trees
Inserting a Node in a Splay Tree
▪ Although the process of inserting a new node N into a splay tree begins in
the same way as we insert a node in a binary search tree, but after the
insertion, N is made the new root of the splay tree.
▪ The steps performed to insert a new node N in a splay tree can be given as
follows:
▪ Step 1 Search N in the splay tree. If the search is successful, splay at
the node N.
▪ Step 2 If the search is unsuccessful, add the new node N in such a way
that it replaces the NULL pointer reached during the search by a
pointer to a new node N. Splay the tree at N.
▪ If the search is successful and N is not the root node, then let P be the
parent of N. Replace N by an appropriate descendent of P (as we do in
binary search tree). Finally splay the tree at P.
▪ This advantage centers on the fact that the splay tree is a self-balancing and a
self-optimizing data structure in which the frequently accessed nodes are moved
closer to the root so that they can be accessed quickly.
▪ Splay trees are considerably simpler to implement than the other self-balancing
binary search trees, such as red-black trees or AVL trees, while their average case
performance is just as efficient.
▪ Splay trees minimize memory requirements as they do not store any book-keeping
data.
▪ Unlike other types of self-balancing trees, splay trees provide good performance
(amortized O(log n)) with nodes containing identical keys.
Splay Trees
The disadvantages of using a splay tree are:
▪ While sequentially accessing all the nodes of a tree in a sorted order, the resultant tree
becomes completely unbalanced.
▪ This takes n accesses of the tree in which each access takes O(log n) time.
▪ For example, re-accessing the first node triggers an operation that in turn takes O(n)
operations to rebalance the tree before returning the first node.
▪
▪ Although this creates a significant delay for the final operation, the amortized
performance over the entire sequence is still O(log n).
▪ For uniform access, the performance of a splay tree will be considerably worse than a
somewhat balanced simple binary search tree.
▪ For uniform access, unlike splay trees, these other data structures provide worst-case
time guarantees and can be more efficient to use.
Problem Statement
Title: Querying in Wireless Sensor
Networks (WSN):
▪ Therefore, worst case time required to get the ID of a node is O(n), where n
is number of nodes in the network.
▪ Yes, if we choose binary search over the liner search. Then the worst case
search time is O(log2(n)).
▪ This suggests that we can use TREES as data structures to store the
information (that is given in the table) and then perform the following
operations: insert, delete, search, sort, find min and max, etc.
Problem Statement
▪ Now that you have identified the right data structure – the trees, your next
job is to identify the appropriate tree that can help us to solve our problem.
▪ Assuming that you have studied the following trees: Binary trees, Binary
Search Trees, AVL, Trees, Red-Black Trees, Splay Trees, Fibonacci Heaps,
B-Trees and B+ Trees, choose the right one to solve the problem.
▪ After identifying the right choice, give explanation why that is the best
choice to solve the given problem and why not other choices.
▪ Write a C++ program to simulate the tree that you identified as the right
choice and show how it solves our problem (the task of identifying the location
of the sensors with minimum time).
Grand
Child Children
198
Logical Relationships
The structures of the data can be viewed in two ways:
▪ Physically:
▪ The physical data structure refers to the physical arrangement of the data
on the secondary storage device, usually disk.
▪ Typically, this physical structure is the concern of specialists who design
DBMSs.
▪ Analysts, programmers, and users are generally less concerned with the
physical structure than with the logical structure.
Note: You can skip this slide in case you are aware of the topic.
Logical Relationships
▪ Logically:
▪ The logical data structure concerns how the data "seem" to be arranged and the
meanings of the data elements in relation to one another
▪ This structure, or model, is generally defined in terms of a schema - an overall
conceptual view of the logical relationships between the data elements in the system.
▪ It includes the names of the major elements, their attribute (features), and the logical
relationships between them
Note: You can skip this slide in case you are aware of the topic.
Logical Relationships
▪ The figure below shows a schema of auto
(vehicle) parts store.
▪ It illustrates that relationships exist between Part # Description Cost
part numbers, types of cars, models, and
manufactures.
▪ The connecting lines indicate links and the
arrows the type of relationship.
Model
▪ For example, in this schema, manufacturer is
linked to part number, and the relationship in
one-to-many (a double-headed arrow implies
many and single-headed arrow one).
▪ That is, one manufacturer produces many part Type of Vehicle
numbers, but each part number has only one
manufacturer. There are also indirect links
indicated.
▪ A part number, for example, is linked to type Manufacturer
of vehicle through model.
Abstract Data Type
▪ An Abstract Data Type (ATD) is an abstraction (idea) of a data structure which
provides only the interface to which a data structure must adhere to.
▪ The interface does not give any specific details about how something should be
implemented or in what programming language.
▪ Example
Abstraction (ADT) Implementation (DS)
List Dynamic array and Linked list
Queue Linked list based queue, Array based queue
and Stack base queue.
Map Tree map, Hash map or Hash table
Vehicle Golf card or bicycle or smart car
[Link]
Recap
[Link]
[Link]
PLTGE29FJfNpXEhADyWwmjdko5bVUr0qvz5RM
8
45 45
2 7
36 63 63
36
4 6
27 54 72 54
1 39 3 27 39 72
5
70
1
Objective: The objective(s) of this experiment is:
1) Reverse the given string with the help of
stacks that are implemented using arrays.
Mid-1 pattern
15 MCQ * 1 = 15 marks
Reg_no [Link]