Data Structure
Data Structure
Example
int marks[2];
marks[0]= 20;
marks[1]= 50;
Accessing array elements using loops
❖ int marks[5];
for(int i=0; i<5;
i++) marks[i]=i
Input and Output Values of an Array
Write a program that inputs five integers from the user and stores them in an array. It then displays all valu
the array using loops
Output
#include<iostream>
Enter an integer: 96
using namespace std; Enter an integer: 72
int main(){ Enter an integer: 41
int array[5], i; Enter an integer: 39
for(i=0; i<5; i++) Enter an integer: 68
{ The values in array
cout<<“Enter an integer:”; are: 96
cin>> arr[i]; 72
} 41
cout<<“The values in array are: \n; 39
for(i=0; i<5; i++) 68
cout<<arr[i]<<endl;
return;
}
Operations on Linear Arrays
Several Operations can be performed on linear arrays.
The most important of these operations include
• Traversing
• Inserting
• Deleting
• Searching & Sorting
Traversing Operation
In traversing operation, each element of an array is access exactly once for processing
For example, to compute the sum of values of each element of an array, all elements of array are
accessed exactly once and their values are added.
Inserting Operation
In inserting operation, new items are added into an array. A new item can be added:
• At the end of array without disturbing other elements of the array if there is an empty element.
• At some specified location within the array
Inserting Value at Specified Location in an Array
0 1 2 3 4
12 15 3 100 92
item
Deleting Operation
Deleting item from a Specified Location
To remove the item from the array at specified location
• By removing the item, Items from the location up to end of array are moved one location towards
the beginning of the array.
• The size of array also decrease
Index
0 1 2 3 4
12 15 3 100 92
item
Algorithm – Deleting item from array
1. Start
2. Input location in K
3. Input array length in N
4. IF K > =N || K < 0 then
1. Print “Invalid Location”
2. Return
3. END IF
5. Repeat For C = K To N-1
1. Arr[C] = Arr [ C+1]
2. C = C+1
6. Arr[N-1] = 0
7. Exit
Searching and Sorting Arrays
The process of finding a specific data item and its location is called searching
These are different searching techniques
• Linear Search
• Binary Search
Syntax
Data_Type identifier[Rows][Cols]
Data_Type It indicates the data types of the values to be stored in the array It
Identifier indicates the name of the array
Rows It indicates the number of rows in the 2-D array It
Cols indicates the number of columns in the array
Example
❖ The following statement declares a 2-D array with four rows and three
columns:
• Int Arr[4][3];
Two-Dimensional Arrays
The statement int Arr[4][3];
❖ The statement declares a two-dimensional array. The first index indicates array contains four
rows.
❖ The index of first row is 0 and the index of last row is 3.
❖ The second index indicates that each row in the array contains three columns.
❖ The index of first column is 0 and the index of last column is 2.
❖ The total number of elements can be determined by multiplying rows and columns.
❖ The above array contains twelve elements
0 1 2
0 0,0 0,1 0,2
Column indexes
1 1,0 1,1 1,2
Row indexes 2 2,0 2,1 2,2
01 2 3
0
12 5 22 84
1 95 3 41 59
2 77 6 53 62
Searching in Arrays
Searching is the process of finding the required data in the array. Searching becomes more
important when the length of the array is very large.
Sequential Search
Sequential search is also called linear search or serial search. It is a simple way to search an array
for the desired value. It follows the following steps to search a value in array:
• Visit the first element and compare its value with the required value.
• If the value of array matches with the desired value, the search is complete.
• If the value of array does not match, move to next element and repeat same process.
Loops are frequently used to visit elements of array for searching a value. You can start the counter
variable of loop from 0 and move it to last index of array. For example if the array to be searched
has 10 elements, the loop will start the counter variable from 0 and move to 9.
Algorithm: Linear Sequential Search
1. SET LOC = -1
2. INPUT ITEM [Enter value that is to be searched]
3. REPEAT STEP-4 FOR I = 0 TO N
4. IF ITEM = ABC[I] THEN
LOC = I
EXIT
5. END IF[End of step-3 loop]
6. IF LOC = -1 THEN
PRINT "Item not Found"
ELSE
PRINT “Item Found at location”
END IF
7.
Binary Search
Binary search is a quicker method of searching for value in the array.
Binary search is very quick but it can only search an sorted array.
Search Element 45
Sorted Array
1 3 16 20 32 50
Index: 0 1 2 3 4 5
Binary Search Example
Start 0
end 6
mid 3
First Iteration:
1 3 16 20 32 45 50
Index: 0 1 2 3 4 5 6
Binary Search Example
Start 4
end 6
mid 5
Second Iteration:
1 3 16 20 32 45 50
Index: 0 1 2 3 4 5 6
Binary Search Example
Start 5
end 6
mid 5
Third Iteration:
1 3 16 20 32 45 50
Index: 0 1 2 3 4 5 6
class StackADT{
private:
int array[10] = {1, 2, 4 , 5, 10, 11, 13, 14, 17, 20};
public:
void push(int item);
void pop();
};
Abstract Data Types
An abstract data type is a set of data together with a set of operations.
Objects such as lists and sets along with their operations can be viewed as ADTs.
The C++ class allows for the implementation of ADTs, with appropriate hiding of
implementation details
Benefit of Abstract data type
❖ If someone wants to use stack in the program, then he can simply use the push and pop
• operations without knowing its implementation
❖ If for some reasons implementation details need to be changed.
❖ For example the implementation of stack is changed from array to linked list it does
not affect the user, he can just use abstract data type by calling its functions
❖ So abstract data type provides abstraction
STACKS
STACKS
• A stack is a special kind of linear list in which only two operations, insertion and deletion can be
performed.
• These operations may occur only at its top end.
• Items in it are stored and retrieved in Last In First Out (LIFO) Push Pop
items
item3
item2
STACK
item1
Representation of Stacks
A stack is usually represented by a linear array in the computer memory
Top
Bottom
66 75 77 69
0 1 2 3 4 5 6 7
The most accessible item in the stack is called the Top of the stack.
The least Accessible Item is called Bottom of the stack
Stack Operations
The only two operations that can be performed on a stack are insertions and deletion
Pushing
• The process of inserting or adding new items into stack is called Pushing.
• Before pushing an item into a stack, it is tested whether or not there is any room in the stack to store
item.
• If there is no room in the stack, then the stack condition is known as a overflow
Popping
• The process of removing or deleting item from a stack is called Popping.
• Before removing an item from a stack it is tested whether or not at least one element exists in the
stack.
• If no element exists in a stack, i.e. the stack is empty, the condition is known as underflow.
Push Procedure – Push(Item)
1. START
2. IF TOP =N-1 THEN
1. PRINT “STACK OVERFLOW”
2. RETURN
3. ENDIF
4. TOP = TOP +1
5. S[TOP] = ITEM
6. END
Pop Procedure – Pop()
1. START
2. IF TOP =-1 THEN
1. PRINT “STACK UNDERFLOW”
2. RETURN
3. ENDIF
4. TOP = TOP -1
5. ITEM = S[TOP]
6. RETURN ITEM
7. END
Evaluation of Expressions
● An arithmetic expression is made up of operands, arithmetic operators and parentheses.
● The operands may be numeric variables or numeric constants
● The arithmetic operators +, -, * and / are the same that are used in ordinary algebra
● The operator ^ is used as to compute the exponential.
X+Y +XY
X/Y /XY
(X + Y) * Z *+XYZ
Reverse Polish Notation or Postfix Notation
In this notation the arithmetic operator is placed after the operands. This notation is also known as suffix
notation.
The following shows expressions in infix notation and equivalent prefix and postfix notations.
1. The express is scanned from left to right until the end of the expression.
2. When an operand is encountered, it is pushed into stack.
3. When an operator is encountered, then:
a. The top two operands of stack are removed
b. The arithmetic operation is performed
c. The computed result is pushed back to the stack
4. When end of the expression is reached, the top value from the stack is picked. It is the computed
value of the expression.
Evaluation of Expression in Computer
Evaluate expression AB/C-DE*+ when A=12, B=6, C=3, D=4 & E=5
A=12
A=12
Evaluation of Expression in Computer
Evaluate expression AB/C-DE*+ when A=12, B=6, C=3, D=4 & E=5
2
Evaluation of Expression in Computer
Evaluate expression AB/C-DE*+ when A=12, B=6, C=3, D=4 & E=5
-1
Evaluation of Expression in Computer
Evaluate expression AB/C-DE*+ when A=12, B=6, C=3, D=4 & E=5
E=5
Iteration 7 : Push the E into stack
D=4
-1
The infix expression is converted into postfix expression according to the following rules:
1. The infix expression is scanned from left to right until end of the expression. The operand are passed
directly to the output. Whereas, the operator are first passed to the stacks
2. Whereas an operand is encountered, it is added to the output, i.e. to the postfix expression.
3. Each time an operator is read, the stack is repeatedly popped and passed to the output, until an
operator is reached that has a lower precedence than the most recently read operator. The most
recently read operator is then pushed onto the stack.
4. When end of expression is reached, then all operators from stack are popped and added to the
output.
Infix to Postfix Conversion
5. Parentheses can be used in the infix expression but these are not used in the postfix expression.
During conversion process, parentheses are treated as operators that have higher precedence than
any other operator. The left parenthesis is pushed into the stack when encountered.
6. The right parenthesis is never pushed to the stack. The left parenthesis is popped only when right
parenthesis is encountered. The parentheses are not passed to the output postfix expressions; they
are discarded.
7. When end of expression is reached, then all operators from stack are popped and added to the
output.
Infix to Postfix Conversion
Convert the following infix expression in postfix expressions:
● (A + B) * C
● A + ( B * C)
● A+ B * C + (D * E + F) * G
Infix to Postfix Conversion
(A + B) * C
(A+ B) * C )
1 ( (
2 ( ((
3 A (( A
4 + ((+ A
5 B ((+ AB
6 ) ( AB+
7 * (* AB+
8 C (* AB+C
9 ) AB+C*
Infix to Postfix Conversion
A + (B * C)
A + (B * C))
1 ( (
2 A ( A
3 + (+ A
4 ( (+( A
5 B (+( AB
6 * (+(* AB
7 C (+(* ABC
8 ) (+ ABC*
9 ) ABC*+
Infix to Postfix Conversion
A + B* C + (D * E + F) * G
A + B* C + (D * E + F) * G)
1 ( (
2 A ( A
3 + (+ A
4 B (+ AB
5 * (+* AB
6 C (+* ABC
7 + (+ ABC*+
8 ( (+( ABC*+
9 D (+( ABC*+D
Infix to Postfix Conversion
A + B* C + (D * E + F) * G
A + B* C + (D * E + F) * G)
10 * (+(* ABC*+D
11 E (+(* ABC*+DE
12 + (+(+ ABC*+DE*
13 F (+(+ ABC*+DE*F
14 ) (+ ABC*+DE*F+
15 * (+* ABC*+DE*F+
16 G (+* ABC*+DE*F+G
17 ) ABC*+DE*F+G*+
Infix to Prefix Conversion
The stack is used to convert an infix expression to postfix. The stack is used to store operators and then
pass to the prefix expression according to their precedence.
The infix expression is converted into prefix expression according to the following rules:
1. Reverse the infix expression
2. Convert the reversed infix expression to “nearly” postfix expression.
3. While converting to postfix expression, instead of using pop operation to pop operators with greater
than or equal precedence, here we will only pop the operators from stack that have greater
precedence.
4. Reverse the postfix expression.
Infix to Prefix Conversion
Convert the following infix expression in postfix expressions:
● A*B+C/D
● (A – B / C) * ( A/ K - L)
Infix to Prefix Conversion
A*B+C/D
D/C+B*A Steps Symbol Scanned Stack Output
D / C + B * A) 1 (
2 D ( D
3 / (/ D
4 C (/ DC
5 + (+ DC/
6 B (+ DC/B
7 * (+* DC/B
8 A (+* DC/BA
9 ) DC/BA*+
+*AB/CD
Infix to Prefix Conversion
(A-B/C) * (A/K-L)
(L-K/A)*(C/B-A)
(L-K/A)*(C/B-A))
1 (
2 ( ((
3 L (( L
4 - ((- L
5 K ((- LK
6 / ((-/ LK
7 A ((-/ LKA
8 ) ( LKA/-
9 * (* LKA/-
Infix to Prefix Conversion
(A-B/C) * (A/K-L)
(L-K/A)*(C/B-A)
(L-K/A)*(C/B-A))
10 ( (*( LKA/-
11 C (*( LKA/-C
12 / (*(/ LKA/-C
13 B (*(/ LKA/-CB
14 - (*(- LKA/-CB/
15 A (*(- LKA/-CB/A
16 ) (* LKA/-CB/A-
17 ) LKA/-CB/A-*
*-A/BC-/AKL
Recursion
A procedure that calls itself, either directly or indirectly, is called recursive procedure and the process is
called recursion.
• There must be a criteria for existing from the recursive procedure. The condition at which the control
exits from procedure is known as the Base Criteria
• Each time the procedure is called directly or indirectly, the condition must get closer to the Base
Criteria
Implementation of Recursive Procedure by Stacks
A recursive procedure can be executed several times. It receives values from the calling procedure and
transmits results back to it.
The recursive function terminates execution when the base criteria is reached. It then returns parameters
and variables to the calling procedures. It return these values such that the values from the last execution
are returned first.
The last-in and first-out characteristics of a recursive procedure shows that a stack is the most suitable
data structure to implement it.
Recursive Procedure Example
FACTORIAL (N)
1. IF N = 0 THEN
RETURN 1
ELSE IF
RETURN N * FACTORIAL(N-1)
QUEUE
Queue
A queue is a special type of linear structure. It holds a series of items for processing on a first in first out
basis.
Element can only be inserted to the Rear of a queue, and deleted from Front of queue.
Example
• An example of a queue in real world is a queue of people waiting to buy tickets. The person who
came first in the queue will be given the ticket first. The person who joined the queue at last time is
entertained last.
• The position of the first person is not changed if a new person joins the queue because he is added at
the end.
• The positions of all persons in the queue are changed when the first person buys the ticket and leaves
the queue. In this situation, each person in the queue moves one step forward.
Queue Data Structure
Representation of Queue
A queue can be represented in computer in two ways:
0 1 2 3 4 5 6 7
Rear Front
Queue - Insertion
Insertion Deletion Front = 0
Rear = 0
45
0 1 2 3 4 5 6 7
Rear Front
Insertion Deletion Front = 0
Rear = 1
45 21
0 1 2 3 4 5 6 7
Rear Front
Queue - Insertion
Insertion Deletion Front = 0
Rear = 2
45 21 77
0 1 2 3 4 5 6 7
Rear Front
Insertion Deletion Front = 0
Rear = 3
45 21 77 23
0 1 2 3 4 5 6 7
Rear Front
Queue - Deletion
Insertion Deletion Front = 1
Rear = 3
21 77 23
0 1 2 3 4 5 6 7
Rear Front
Insertion Deletion Front = 2
Rear = 3
77 23
0 1 2 3 4 5 6 7
Rear Front
Algorithm - Insertion
1. START
2. IF R == N THEN
PRINT “Overflow”
RETURN
ELSE
R=R+1
Q[R] = Item
ENDIF
3. IF F = -1 THEN
F=0
END IF
4. EXIT
Algorithm - Deletion
1. START
2. IF F=-1 THEN
PRINT “Underflow”
RETURN
ENDIF
3. Del = Q[F]
4. IF F = R THEN
F = R = -1
ELSE
F=F+1
END IF
5. EXIT
Circular Queue
Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In
First Out) principle and the last position is connected back to the first position to make a circle.
0
12 1
42
5 92
43 2
22
16
4
3
Algorithm - Insertion
1. START
2. IF (R+1)%N = F THEN
PRINT “Overflow”
RETURN
ELSE
R = (R + 1)%N
Q[R] = Item
ENDIF
3. IF F = -1 THEN
F=0
END IF
4. EXIT
Algorithm - Deletion
1. START
2. IF F=-1 THEN
PRINT “Underflow”
RETURN
ENDIF
3. Del = Q[F]
4. IF F = R THEN
F = R = -1
ELSE
F = (F + 1)%N
END IF
5. EXIT
Priority Queue
• A priority queue is a more specialized data structure than a stack or a queue.
• Like an ordinary queue, a priority queue has a front and a rear, and items are removed from the front.
• However, in a priority queue, items are ordered by key value so that the item with the lowest key (or
in some implementations the highest key) is always at the front. Items are inserted in the proper
position to maintain the order.
• Like ordinary queues, priority queues are used in various ways in certain computer systems. In a
preemptive multitasking operating system, for example, programs may be placed in a priority queue
so the highest-priority program is the next one to receive a time-slice that allows it to execute.
Priority Queue
Q1
0 1 2 3 4
Q2
0 1 2 3 4
Q3
0 1 2 3 4
Q4
0 1 2 3 4
Deques
• The term deque stands for double-ended queue. Items can be added or deleted at both ends of the
deque, it is called double-ended queue
Deletion Deletion
Insertion Insertion
0 1 2 3 4
Front Rear
Insertion at Front
Front = -1
Rear = -1
0 1 2 3 4 5 6 7
Insertion at Front
Front = 0
Rear = 0
20
0 1 2 3 4 5 6 7
Front = 7
Rear = 0
20 30
0 1 2 3 4 5 6 7
Insertion at Front
Front = 6
Rear = 0
20 32 30
0 1 2 3 4 5 6 7
Front = 5
Rear = 0
20 11 32 30
0 1 2 3 4 5 6 7
Algorithm – Insertion At Front
1. START
2. IF F=0 && R = N-1 || F = R+1 THEN
PRINT “Overflow”
RETURN
3. IF F = -1 THEN
F= R = 0
ELSE IF F = 0 THEN
F= N-1
ELSE
F= F-1
END IF
Q[F] = Item
4. EXIT
Deletion at Front
Front = 5
Rear = 0
20 11 32 30
0 1 2 3 4 5 6 7
Front = 6
Rear = 0
20 32 30
0 1 2 3 4 5 6 7
Deletion at Front
Front = 6
Rear = 0
20 32 30
0 1 2 3 4 5 6 7
Front = 7
Rear = 0
20 30
0 1 2 3 4 5 6 7
Deletion at Front
Front = 0
Rear = 0
20
0 1 2 3 4 5 6 7
Algorithm – Deletion At Front
1. START
2. IF F=-1 THEN
PRINT “Underflow”
RETURN
3. Item = Q[F]
4. IF F = R THEN
F= R = -1
ELSE IF F = N-1 THEN
F= 0
ELSE
F= F+1
END IF
5. EXIT
Insertion at Rear
Front = -1
Rear = -1
0 1 2 3 4 5 6 7
Front = 0
Rear = 0
20
0 1 2 3 4 5 6 7
Insertion at Rear
Front = 0
Rear = 1
20 7
0 1 2 3 4 5 6 7
Front = 0
Rear = 2
20 7 13
0 1 2 3 4 5 6 7
Algorithm – Insertion At Rear
1. START
2. IF F=0 && R = N-1 || F = R+1 THEN
PRINT “Overflow”
RETURN
3. IF R = -1 THEN
F= R = 0
ELSE IF R = N-1 THEN
R= 0
ELSE
R= R+1
END IF
Q[R] = Item
4. EXIT
Deletion at Rear
Front = 0
Rear = 2
20 7 13
0 1 2 3 4 5 6 7
Front = 0
Rear = 1
20 7
0 1 2 3 4 5 6 7
Deletion at Rear
Front = 0
Rear = 0
20
0 1 2 3 4 5 6 7
Front = -1
Rear = -1
0 1 2 3 4 5 6 7
Algorithm – Deletion At Rear
1. START
2. IF R=-1 THEN
PRINT “Underflow”
RETURN
3. Item = Q[R]
4. IF F = R THEN
F= R = -1
ELSE IF R = 0 THEN
R= N-1
ELSE
R= R-1
END IF
5. EXIT
MID TERM
Linked Lists
Linked Lists
Elements of an array are stored sequentially in the memory. The sequential storage is not either possible
or efficient in larger computer systems
Array is static data structure. The size of array cannot be changed during the program execution
0x0064df0
The memory address is a hexadecimal number that refers to a particular location in the
memory
The use of pointer to link elements of a data structure implies that elements need not be
physically adjacent in the memory. They can be stored anywhere in the memory but they
logically remain adjacent. This type of storage is called linked storage.
Single Linked List
A single Linked list is a linear collection of data elements. The elements in a single linked list can be
visited starting from beginning and towards its end only in one direction
1010
The Variable Start (called list pointer variable) contains the memory address of the first node of the list.
It points to starting memory location of the linked list. The linked list is accessed with reference to this
pointer variable.
Node has two parts
• One for actual value
• Second for next node address
Representation of Linked List in Memory
The storage technique of linked lists is different from that of linear arrays.
Each item of linked list contains at least two fields.
One field is used to store data and the other to store address of memory location of the next object.
In this way the objects of list are linked together in the form of a chain.
The following example explains this concept using C++ structure
struct node{
int data;
Node *link;
};
node *start;
Operation on Single Linked List
1. Traversing
2. Inserting
Add to Beginning
Add to End
Add to The middle
3. Deleting
Add to Beginning
Add to End
Add to The middle
Insertion
At the beginning
1000
1010 FSC
1000
Insertion
At the beginning
struct node{
int data;
1. Allocate memory to new node
node *link;
2. Store data
};
3. Change next of new node to point to head
node *newNode = new node;
4. Change head to point recently created node
newNode -> data = 40;
newNode -> next = start;
start = newNode
Insertion
At the end
1010
NULL Post
Phd
3020
Insertion
At the end
struct node{
int data;
1. Allocate memory to new node
node *link;
2. Store data
};
3. Traverse to last node
node *newNode = new node;
4. Change next of last node to recently created node
newNode -> data = 40;
newNode -> next = null;
node *temp = start;
while(temp->next !=null)
temp = temp->next
temp->next = newNode
Insertion
At the middle
1010
3010 Post
Phd
3020
Insertion
At the middle
struct node{
int data;
1. Allocate memory to new node
node *link;
2. Store data
};
3. Traverse to node just before the position
node *newNode = new node;
4. Change the pointer to insert newnode between
newNode -> data = 40;
node *temp = start;
int pos, i;
for(i=2; i< pos ; i++){
if(temp -> next !=null)
temp = temp->next;
}
newNode -> next = temp->next;
temp->next = newnode;
Deletion
At the beginning
1080
2090 MSC
1080
Deletion
At the middle
At the beginning
Traverse to element before the element to
Point head to second node deleted
head = head -> next Change next pointer
for(i=2; i<position; i++){
if(temp->next != null)
At the end temp = temp->next
Traverse to second last element }
Change its next pointer to null temp->next = tempt->next->next
node * temp = start
while(temp->next->next !=null
temp = temp->next
temp->next = Null
Algorithm _ Creating Linked List
1. DEFINE structure of node
2. DECLARE three pointer objects start, current & temp of type node
3. IF start =NULL
[Create first node and assign its address to “start”. Also assign value to the node]
start = new-node
start->data = data
start->link = NULL
4. ELSE
[Assign address of start node to the current node to proceed next]
current = start
while(current -> link != NULL)
Create new node
[Assign value and address of new node to current node and address of new-node to current]
temp = new-node
temp -> data = data
current->link = tem
5. Exit
Double Linked List
A linear list in which each node has the addresses each of next node and of the previous node is calle
double linked list. A double linked list can be visited in both directions, i.e. in forward and backward
direction. It is also called two-way list.
1010
The Variable Start (called list pointer variable) contains the memory address of the first node of the list.
It points to starting memory location of the linked list. The linked list is accessed with reference to this
pointer variable.
Node has three parts
• One for actual value
• Second for next node address
• Third for previous node address
Representation of Double Linked List
The double-linked list is represented in the memory as a data structure having at least three fields. In
C++, it is defined as:
struct node{
node * previous;
int data;
node * next;
} *start, *pn, *temp
Algorithm – Creating Double–Linked List
Write a algorithm to create a double-linked list consisting of ten nodes.
Suppose X is data field of the node and p & n are its pointer fields for previous and next nodes,
respectively
1. REPEAT Step-2 For C=1 to 10
2. temp = new node
IF C =1 Then
Start = temp
Start -> p = Null
Start -> X = Value
Start -> n = Null
pn = temp
Else
pn -> n = temp
temp -> p = pn
temp ->X = Value
pn= temp
3. Exit
Double-Linked List Operations
Like single-linked lists, the following operations can be performed on the double linked list.
● Traversing
○ Forward Direction
○ Backward Direction
● Insertion
○ At Begin
○ At Middle
○ At End
● Deletion
○ At Begin
○ At Middle
○ At End
Traverse double Linked List
Forward
Start from head/start pointer
visit all nodes by referencing and access node data
Reverse
Start from head/start pointer
visit all nodes by referring and reach last node
Access node data by referring all nodes in reverse direction
1010
Properties:
Edge: Edge is a connection between one node to another. The line drawn from a parent
node to its child node is called an edge.
Path: Path is a number of successive edges from source node to destination node.
Parent: The node above a node (or immediate predecessor of a node) is called the parent of
that node.
Tree Terminology
Child: The nodes that are directly linked in a node one level above them (or immediate
successors of a node) are called child nodes or children to the parent node.
Siblings: The nodes that share a parent node are a set of sibling nodes.
Leaf: A node that has no children is called leaf node or a leaf. These are also called leaf
nodes.
Subtree: A set of all nodes that consists of any node (except the root) and all nodes below that
node is called subtree.
Tree Terminology
Levels: The level of a particular node refers to its position in the tree. The root node is the top
level node and can be referred as level 0. The children are at level 1 and grandchildren at level
2 and so on.
Depth of Node: Depth of a node represents the number of edges from the tree’s root node to
that node.
Height of Node: Height of a node is the number of edges on the longest path between that
node and a leaf.
Example of a non-tree
Binary Tree
A binary tree is a tree-type non-linear data structure with a maximum of two children for each
parent. Every node in a binary tree has a left and right reference along with the data element.
The node at the top of the hierarchy of a tree is called the root node.
In other words, if in a binary tree a node contains only one child node, it is not a full binary tree.
Complete Binary Tree
In a complete binary tree
● All the levels are completely filled except the last level that may or may not be completely
filled.
● Elements are filled from left to right.
Perfect Binary Trees
If in a tree all the internal nodes have exactly two children nodes, it is known as a perfect binary
tree
In a perfect binary tree, all the leaf nodes are on the same level.
Degenerate Binary Trees
If in a binary tree each node contains only one child node either on the left side or the right side
of the tree, it is known as a degenerate binary tree.
Left-skewed Right-skewed
Balanced Binary Trees
A binary tree is said to be balanced if the height of the left and the right subtrees differ by 0 or
1.
In a balanced binary tree, both the left and right trees are also balanced.
Traversing Binary Tree using Iteration
1. Preorder (Node - Left - Right)
2. Inorder (Left - Node - Right)
3. Postorder (Left - Right - Node)
Push Pop
A
B C
D E F
G
Inorder Traversing Binary tree Using Stack
1. Proceed down to left most path push each node N on the stack. Stop when node n with no
left child pushed onto stack.
2. Pop and Process the node on stack Push Pop
a. If null is popped exit
b. if a node N with Right child is processed and repeat step 1
A
B C
D E F
G
Postorder Traversing Binary tree Using Stack
1. Proceed down to left most path pushing each node on stack if N has a Right child push
“-Rightchild”
2. Pop and Process positive node on stack Push Pop
a. if negative node is popped, repeat step 1
b. if Null is popped exit
A
B C
D E F
G
Binary Search Tree
Binary Search tree every node is organised in specific order. This is also called ordered Binary
tree
Suppose T is Binary Tree then T is called (BST) if each node of T has following properties
The value of N is greater than every value in left subtree
The Value of N is less than every value in Right subtree of N. 38
14 56
82
8
23 45
70
18
Binary Search Tree Operations
Operations: 1. Compare ITEM with Root node N
a. if ITEM<N Proceed to left child
1. Search b. If ITEM>N Proceed to Right child
2. Insert 2. Repeat step 1 until one of following occur\
3. Delete a. We meet a node N such that ITEM==N
b. We meet a empty subtree which include
unsuccessful and Insert item at empty
38 location
14
56
8 23 45 82
18 70
Binary Search Tree Operations
Delete Case 1: Node is leaf node
Operation Case 2: Node has only child
Case 3: Noe has two child
38
14
56
8 23 45 82
18 70
AVL Tree
AVL Tree can be defined as height balance binary search tree in which each node is associated
with Balance Factor (BF) 0, 1, -1.
BF = 1 38 BF = 2
38
BF = -1 14 56
BF = -1 14 56
82 8
8 45
23 45 23
70
18 18
AVL Tree
Rotation:
1. Left - left Rotation (LL-Rotation)
2. Right- Right Rotation (RR-Rotation)
3. Left - Right Rotation (LR-Rotation)
4. Right - left Rotation (RL-Rotation)
38 BF = 2
38 BF = 2
14 56
14
8
23 45
8
18
AVL Tree Insertion
Construct the AVL search tree by Inserting the following element
64, 1, 14, 26, 13, 110, 98, 85
14
1 64
98
13 26
110
85
AVL Tree Deletion
30
Deletion is similar as binary search tree. After deletion we reconstruction the tree
if needed to maintain it height.
20 40
Step 1: Find element in the tree
Step2: Delete the node as BST Rule
Step 3: Two case are possible if tree is unbalanced.
Case 1: Deletion from Right subtree 10
i) if BF(N) = +2 and BF(N -> LC)= +1, do LL Rotation
ii) if BF(N) = +2 and BF(N->LC)= -1, do LR Rotation 30
iii) if BF(N) = +2 and BF(N -> LC)=0, do LL Rotation
Case 2: Deletion from :Left subtree
i) if BF(N) = -2 and BF(N -> RC)= -1, do RR Rotation 20
ii) if BF(N) = -2 and BF(N->RC)= +1, do RL Rotation 40
iii) if BF(N) = -2 and BF(N -> RC)=0, do RR Rotation
50
Graph
Graphs
Graphs are non-linear data structures. A graph is made up of sets of nodes and lines. Nodes
are called vertices. Lines are called edges. Lines are used to connect nodes. An edge of the
graph is represented as:
e = [u, v]
‘u’ and ‘v’ denote the start and end nodes of edge ‘e’, respectively. They are also known as
the tail and head nodes of edge ‘e’.
LAHORE KARACHI
ISLAMABAD
SAHIWAL
FAISALABAD
Graphs
Undirected Graphs
An undirected graph has edges that have no direction. An undirected graph is also called
an undigraph.
Directed Graphs
A direct graph has edges that are unidirectional. A directed graph is also called a digraph.
Weighted Graphs
A graph which has a weight, or number, associated with each edge is called weighted
graph.
Degree of Node
The number of edges that a node contain is called degree of the node.
Graphs
Out-degree & In-degree
The number of edges beginning from a node is called the out-degree of the node. The
number of edges at a node is called the In-degree of the node.
C D
Path & Length of Graph
A list of nodes of a graph where each node has an edge from it to the next node is called
the path.
Loop Edge
An edge ‘e’ is said to be a loop edge if it has the same node at its tail and head.
Representation of Graphs
Graphs are unstructured. One vertex in a graph might be adjacent to every other vertex. The
adjacency list is used to represent the graph in memory.
Adjacency List
An adjacency list is array of listed lists, on for each vertex. Each linked list contains all of
the vertices that are adjacent to a given vertex.
A E
C D
Adjacency List
A E B
A E
B C
B
C D E
D E
C D
E
Depth-First Search
In Depth First Search (DFS), the search can be started from any vertex in the graph
Algorithm – DFS
1. Visiting first node and its neighbors along the path p of a graph
2. Set the status of all nodes to ready state
3. Push the starting node A onto the stack and set its status to the waiting state.
4. Repeat step-5 to 6 until stack is empty
5. Pop the top node of stack, process it and set its status to process state.
6. Push all the neighbour of A onto the stack that have status of ready state and set their
status to the waiting state.
[End of loop at step-4]
A E
7. Exit
B
C D
Breadth-First Search
In Breadth – First Search (BFS)
1. Visiting first node and its neighbours of a graph
2. Set the status of all nodes to ready state
3. Put the starting node A into the queue and set its status to the waiting state.
4. Repeat step-5 to 6 until queue is empty
5. Pick the front node of queue, process it and set its status to processed state.
6. Add all the neighbours of A into the queue that have status of ready state and set their
status to the waiting state.
[End of loop at step-4]
7. Exit
A E
C D
Breadth-First Search
A E
B F
C D
G