0% found this document useful (0 votes)
2 views

Data Structures

Data structures are methods for organizing and manipulating data for efficient retrieval and access, with applications in various fields like AI and database management. Key types include linear structures (like arrays and stacks) and non-linear structures (like trees and graphs), each with distinct characteristics and use cases. Stacks follow a Last In First Out (LIFO) principle, while queues operate on a First In First Out (FIFO) basis, with various implementations such as circular queues and priority queues.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Data Structures

Data structures are methods for organizing and manipulating data for efficient retrieval and access, with applications in various fields like AI and database management. Key types include linear structures (like arrays and stacks) and non-linear structures (like trees and graphs), each with distinct characteristics and use cases. Stacks follow a Last In First Out (LIFO) principle, while queues operate on a First In First Out (FIFO) basis, with various implementations such as circular queues and priority queues.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Data Structures

What is a Data Structure?

The Data Structure is the way data is organized (stored) and manipulated for
retrieval and access.

What are some applications of Data Structures?

Numerical analysis, operating system, AI, compiler design, database management,


graphics, statistical analysis, and simulation.

Can you explain the difference between file structure and storage
structure?

 File Structure: Representation of data into secondary or auxiliary memory say


any device such as a hard disk or pen drives that stores data which remains intact
until manually deleted is known as a file structure representation.
 Storage Structure: In this type, data is stored in the main memory i.e RAM, and
is deleted once the function that uses this data gets completely executed.

Describe the types of Data Structures?

1
 Linear Data Structure: A data structure that includes data elements
arranged sequentially or linearly, where each element is connected to its
previous and next nearest elements, is referred to as a linear data structure.
Arrays and linked lists are two examples of linear data structures.
 Non-Linear Data Structure: Non-linear data structures are data structures
in which data elements are not arranged linearly or sequentially. We cannot
walk through all elements in one pass in a non-linear data structure, as in a
linear data structure. Trees and graphs are two examples of non-linear data
structures.

Linear Vs Non-linear Data Structures


Linear Data Structures Non Linear Data Structures

The data items are arranged in The data items are arranged in non-
sequential order, one after the other. sequential order (hierarchical manner).

All the items are present on the The data items are present at different
single layer. layers.

It can be traversed on a single run.


It requires multiple runs. That is, if we
That is, if we start from the first
start from the first element it might not be
element, we can traverse all the
possible to traverse all the elements in a
elements sequentially in a single
single pass.
pass.

Different structures utilize memory in


The memory utilization is not
different efficient ways depending on the
efficient.
need.

The time complexity increase with


Time complexity remains the same.
the data size.

Example: Arrays, Stack, Queue Example: Tree, Graph, Map

2
Stack Data Structure
A stack is a linear data structure that follows the principle
of Last In First Out (LIFO). This means the last element
inserted inside the stack is removed first.

LIFO Principle of Stack


In programming terms, putting an item on top of the stack is
called push and removing an item is called pop.

In the above image, although item 3 was kept last, it was


removed first. This is exactly how the LIFO (Last In First Out)
Principle works.

3
Working of Stack Data Structure
The operations work as follows:

1. A pointer called TOP is used to keep track of the top element in


the stack.
2. When initializing the stack, we set its value to -1 so that we
can check if the stack is empty by comparing TOP == -1.

3. On pushing an element, we increase the value of TOP and


place the new element in the position pointed to by TOP.
4. On popping an element, we return the element pointed to
by TOP and reduce its value.
5. Before pushing, we check if the stack is already full
6. Before popping, we check if the stack is already empty

4
Applications of Stack Data Structure
Although stack is a simple data structure to implement, it is very
powerful. The most common uses of a stack are:

 To reverse a word - Put all the letters in a stack and pop


them out. Because of the LIFO order of stack, you will get the
letters in reverse order.
 In compilers - Compilers use the stack to calculate the value
of expressions like 2 + 4 / 5 * (7 - 9) by converting the
expression to prefix or postfix form.
 In browsers - The back button in a browser saves all the
URLs you have visited previously in a stack. Each time you
visit a new page, it is added on top of the stack. When you
press the back button, the current URL is removed from the
stack, and the previous URL is accessed.
 Check for balanced parentheses in an expression.

Algorithm for Push Operation:


 Check if the stack is full or not.
 If the stack is full ,then print overflow and exit the program.
 If the stack is not full, then increment the top and add the element.

5
Algorithm for Pop Operation:
 Check if the stack is empty or not.
 If the stack is empty ,then print underflow and exit the program.
 If the stack is not empty, then print the element at the top and decrement
the top.

Basic Operations of Stack


There are some basic operations that allow us to perform different actions
on a stack.

 Push: Add an element to the top of a stack


 Pop: Remove an element from the top of a stack
 IsEmpty: Check if the stack is empty
 IsFull: Check if the stack is full

6
What is a Queue?
Queue is the data structure that is similar to the queue in the real world. A queue is a
data structure in which whatever comes first will go out first, and it follows the FIFO
(First-In-First-Out) policy. Queue can also be defined as the list or collection in which
the insertion is done from one end known as the rear end or the tail of the queue,
whereas the deletion is done from another end known as the front end or
the head of the queue.

The real-world example of a queue is the ticket queue outside a cinema hall, where
the person who enters first in the queue gets the ticket first, and the last person
enters in the queue gets the ticket at last. Similar approach is followed in the queue
in data structure.

The representation of the queue is shown in the below image -

Queue follows the First In First Out (FIFO) rule - the item that
goes in first is the item that comes out first.

7
Working of Queue
Queue operations work as follows:

 two pointers FRONT and REAR

 FRONT track the first element of the queue


 REAR track the last element of the queue
 initially, set value of FRONT and REAR to -1

Enqueue Operation

 check if the queue is full


 for the first element, set the value of FRONT to 0
 increase the REAR index by 1
 add the new element in the position pointed to by REAR

Dequeue Operation

 check if the queue is empty


 return the value pointed by FRONT

 increase the FRONT index by 1


 for the last element, reset the values of FRONT and REAR to -1

8
9
Limitations of Queue
As you can see in the image below, after a bit of enqueuing and
dequeuing, the size of the queue has been reduced.

And we can only add indexes 0 and 1 only when the queue is
reset (when all the elements have been dequeued).

After REAR reaches the last index, if we can store extra elements
in the empty spaces (0 and 1), we can make use of the empty
spaces. This is implemented by a modified queue called
the circular queue.
Applications of Queue
 CPU scheduling, Disk Scheduling
 Handling of interrupts in real-time systems.
 Call Center phone systems use Queues to hold people
calling them in order.
 Breadth first search algorithm in graphs

10
Types of Queue

o Simple Queue or Linear Queue


o Circular Queue
o Priority Queue
o Double Ended Queue (or Deque)

Simple Queue or Linear Queue


In Linear Queue, an insertion takes place from one end while the deletion occurs
from another end. The end at which the insertion takes place is known as the rear
end, and the end at which the deletion takes place is known as front end. It strictly
follows the FIFO rule.

The major drawback of using a linear Queue is that insertion is done only from the
rear end. If the first three elements are deleted from the Queue, we cannot insert
more elements even though the space is available in a Linear Queue. In this case, the
linear Queue shows the overflow condition as the rear is pointing to the last element
of the Queue.

Circular Queue
In Circular Queue, all the nodes are represented as circular. It is similar to the linear
Queue except that the last element of the queue is connected to the first element. It
is also known as Ring Buffer, as all the ends are connected to another end. The
representation of circular queue is shown in the below image -

11
The drawback that occurs in a linear queue is overcome by using the circular queue.
If the empty space is available in a circular queue, the new element can be added in
an empty space by simply incrementing the value of rear. The main advantage of
using the circular queue is better memory utilization.

Priority Queue
It is a special type of queue in which the elements are arranged based on the
priority. It is a special type of queue data structure in which every element has a
priority associated with it. Suppose some elements occur with the same priority, they
will be arranged according to the FIFO principle. The representation of priority queue
is shown in the below image -

Insertion in priority queue takes place based on the arrival, while deletion in the
priority queue occurs based on the priority. Priority queue is mainly used to
implement the CPU scheduling algorithms.

There are two types of priority queue that are discussed as follows -

o Ascending priority queue - In ascending priority queue, elements can be


inserted in arbitrary order, but only smallest can be deleted first. Suppose an
12
array with elements 7, 5, and 3 in the same order, so, insertion can be done
with the same sequence, but the order of deleting the elements is 3, 5, 7.
o Descending priority queue - In descending priority queue, elements can be
inserted in arbitrary order, but only the largest element can be deleted first.
Suppose an array with elements 7, 3, and 5 in the same order, so, insertion can
be done with the same sequence, but the order of deleting the elements is 7,
5, 3.

Deque (or, Double Ended Queue)


In Deque or Double Ended Queue, insertion and deletion can be done from both
ends of the queue either from the front or rear. It means that we can insert and
delete elements from both front and rear ends of the queue

Deque can be used both as stack and queue as it allows the insertion and deletion
operations on both ends. Deque can be considered as stack because stack follows
the LIFO (Last In First Out) principle in which insertion and deletion both can be
performed only from one end. And in deque, it is possible to perform both insertion
and deletion from one end, and Deque does not follow the FIFO principle.

The representation of the deque is shown in the below image -

There are two types of deque that are discussed as follows -

o Input restricted deque - As the name implies, in input restricted queue,


insertion operation can be performed at only one end, while deletion can be

13
performed from both ends.

o Output restricted deque - As the name implies, in output restricted queue,


deletion operation can be performed at only one end, while insertion can be
performed from both ends.

14
Differentiate between stack and queue data structure .

Stack Queue
Stack is a linear data structure where Queue is a linear data structure where data is
data is added and removed from the ended at the rear end and removed from the
top. front.
Stack is based on LIFO(Last In First Queue is based on FIFO(First In First Out)
Out) principle principle
Insertion operation in Stack is known Insertion operation in Queue is known as
as push. eneque.
Delete operation in Stack is known as Delete operation in Queue is known as
pop. dequeue.
Only one pointer is available for both Two pointers are available for addition and
addition and deletion: top() deletion: front() and rear()

What are the applications of arrays?

Array data structures are commonly used in databases and other


computer systems to store large amounts of data efficiently. They are also
useful for storing information that is frequently accessed, such as large
amounts of text or images.

What is a linked list data structure? What are the applications


for the Linked list?

It’s a linear Data Structure or a sequence of data objects where elements


are not stored in adjacent memory locations. The elements are linked
using pointers to form a chain. Each element is a separate object, called a
node. Each node has two items: a data field and a reference to the next
node. The entry point in a linked list is called the head. Where the list is
empty, the head is a null reference and the last node has a reference to
null.

15
A linked list is a dynamic data structure, where the number of nodes is not
fixed, and the list has the ability to grow and shrink on demand

Following are some applications of linked list data structure:

 Stack, Queue, binary trees, and graphs are implemented using linked lists.
 Dynamic management for Operating System memory.
 Round robin scheduling for operating system tasks.
 Forward and backward operation in the browser.

Representation of a Linked List


This representation of a linked list depicts that each node consists of two fields. The first
field consists of data, and the second field consists of pointers that point to another
node.

16
Here, the start pointer stores the address of the first node, and at the end,
there is a null pointer that states the end of the Linked List.

Types of Linked Lists

The linked list mainly has three types, they are:

1. Singly Linked List


2. Doubly Linked List
3. Circular Linked List

Singly Linked List


A singly linked list is the most common type of linked list. Each node has data and
an address field that contains a reference to the next node.

Doubly Linked List


There are two pointer storage blocks in the doubly linked list. The first pointer block
in each node stores the address of the previous node. Hence, in the doubly linked
inventory, there are three fields that are the previous pointers, that contain a
reference to the previous node. Then there is the data, and last you have the next
pointer, which points to the next node. Thus, you can go in both directions
(backward and forward).

17
Circular Linked List
The circular linked list is extremely similar to the singly linked list. The only
difference is that the last node is connected with the first node, forming a circular
loop in the circular linked list.

Circular link lists can either be singly or doubly-linked lists.

 The next node's next pointer will point to the first node to form a singly linked
list.
 The previous pointer of the first node keeps the address of the last node to
form a doubly-linked list.

Doubly Circular Linked List:

A doubly circular linked list is a linked list where each node points to its next node
and its previous node and the last node points back to the first node and first node’s
previous points to the last node.

18
Essential Operation on Linked Lists

 Traversing: To traverse all nodes one by one.


 Insertion: To insert new nodes at specific positions.
 Deletion: To delete nodes from specific positions.
 Searching: To search for an element from the linked list.

Difference between Array and Linked List.

Array Linked list

An array is a collection of A linked list is a collection of objects known


elements of a similar data type. as a node where node consists of two parts,
i.e., data and address.

Array elements store in a Linked list elements can be stored anywhere


contiguous memory location. in the memory or randomly stored.

Array works with a static memory. The Linked list works with dynamic memory.
Here static memory means that Here, dynamic memory means that the
the memory size is fixed and memory size can be changed at the run time
cannot be changed at the run according to our requirements.
time.

Array elements are independent Linked list elements are dependent on each
of each other. other.

19
Array takes more time while Linked list takes less time while performing
performing any operation like any operation like insertion, deletion, etc.
insertion, deletion, etc.

Accessing any element in an array Accessing an element in a linked list is


is faster as the element in an array slower as it starts traversing from the first
can be directly accessed through element of the linked list.
the index.

Why Linked List/Why Linked List Over Array?

The following are the reasons to use linked list:

1. Size of the array is fixed. We can not increase the size during the
execution of a program. But the size of the linked is not fixed. We can
increase the size of linked list.
2. As the memory size is fixed in array, there is a possibility of wasting
memory if we don’t use the memory. But in linked list as the size is not
fixed there is no possibility of memory waste.
3. Insertion, and deletion is faster in linked list.

20
Tree Data Structure
A tree is also one of the data structures that represent hierarchical data.

Let's understand some key points of the Tree data structure.

o A tree data structure is a non-linear data structure because it does not store in
a sequential manner. It is a hierarchical structure as elements in a Tree are
arranged in multiple levels.
o In the Tree data structure, the topmost node is known as a root node. Each
node contains some data, and data can be of any type.
o Each node contains some data and the link or reference of other nodes that
can be called children.

Some basic terms used in Tree data structure.

o Root: The root node is the topmost node in the tree hierarchy. In other words,
the root node is the one that doesn't have any parent. In the above structure,
node numbered 1 is the root node of the tree. If a node is directly linked to
some other node, it would be called a parent-child relationship.
o Child node: If the node is a descendant of any node, then the node is known
as a child node.
o Parent: If the node contains any sub-node, then that node is said to be the
parent of that sub-node.
o Sibling: The nodes that have the same parent are known as siblings.

21
o Leaf Node:- The node of the tree, which doesn't have any child node, is called
a leaf node. A leaf node is the bottom-most node of the tree. There can be
any number of leaf nodes present in a general tree. Leaf nodes can also be
called external nodes.
o Ancestor node:- An ancestor of a node is any predecessor node on a path
from the root to that node. The root node doesn't have any ancestors. In the
tree shown in the above image, nodes 1, 2, and 5 are the ancestors of node
10.
o Descendant: The immediate successor of the given node is known as a
descendant of a node. In the above figure, 10 is the descendant of node 5.
o Internal nodes:
o Trees in the data structure have at least one child node known as
internal nodes.
o In trees, nodes other than leaf nodes are internal nodes.
o Sometimes root nodes are also called internal nodes if the tree has
more than one node.

22
o Degree
o In the tree data structure, the total number of children of a node is
called the degree of the node.
o The highest degree of the node among all the nodes in a tree is called
the Degree of Tree.

o Level
o In tree data structures, the root node is said to be at level 0, and the
root node's children are at level 1, and the children of that node at level
1 will be level 2, and so on.
o in a tree each step from top to bottom is called as a Level.

23
o Height
o In a tree data structure, the number of edges from the leaf node to the
particular node in the longest path is known as the height of that node.
o In the tree, the height of the root node is called "Height of Tree".
o The height of a tree (also known as depth) is the maximum
distance between the root node of the tree and the leaf node of
the tree

o Consider the following figure:

o
o Here 8 is the root node. From 8 the longest path is to 4, 7 and 13. So
consider the node 4. From node 8 to node 4 there are 3 nodes that is,
3,6,4. So the height of node 8 is 3 and as 8 is the root node so the
height of the tree is also 3.

24
o Now the height of node 3 is 2 because from node 3 to node 4 or node
7 there are two nodes, that is node 6 and node 4 (in case of node 4)
and node 6 and node 7 (in case of node 7).
o Depth
o In a tree, many edges from the root node to the particular node are
called the depth of the tree.
o In the tree, the total number of edges from the root node to the leaf
node in the longest path is known as "Depth of Tree".
o In the tree data structures, the depth of the root node is 0.
o Simply Level = Depth. The depth will be same as level.

If any confusion please visit the following links for basic terminology:

http://www.btechsmartclass.com/data_structures/tree-terminology.html

https://www.programiz.com/dsa/trees

25
Implementation of Tree
The tree data structure can be created by creating the nodes dynamically with the
help of the pointers. The tree in the memory can be represented as shown below:

The above figure shows the representation of the tree data structure in the memory.
In the above structure, the node contains three fields. The second field stores the
data; the first field stores the address of the left child, and the third field stores the
address of the right child.

Types of Tree data structure


1. General Tree

2. Binary Tree

3. Binary Search Tree

4. Balanced Binary Tree

5. AVL Tree

6. B Tree

26
General tree:
The general tree is one of the types of tree data structure. In the general tree, a node
can have either 0 or maximum n number of nodes. There is no restriction imposed
on the degree of the node (the number of nodes that a node can contain). The
topmost node in a general tree is known as a root node. The children of the parent
node are known as subtrees.

27
Binary tree:
Here, binary name itself suggests two numbers, i.e., 0 and 1. In a binary tree, each
node in a tree can have utmost two child nodes. Here, utmost means whether the
node has 0 nodes, 1 node or 2 nodes.

Types of Binary Tree

o Full/ proper/ strict Binary tree


o Complete Binary tree
o Perfect Binary tree

Full/ proper/ strict Binary tree


The full binary tree is also known as a strict binary tree. The tree can only be
considered as the full binary tree if each node must contain either 0 or 2 children.
The full binary tree can also be defined as the tree in which each node must contain
2 children except the leaf nodes.

28
Let's look at the simple example of the Full Binary tree.

Complete Binary Tree


The complete binary tree is a tree in which all the nodes are completely filled except
the last level. In the last level, all the nodes must be as left as possible. In a complete
binary tree, the nodes should be added from the left.

Let's create a complete binary tree.

29
Perfect Binary Tree

A tree is a perfect binary tree if all the internal nodes have 2 children, and all the leaf
nodes are at the same level.

Binary Search tree


What is a Binary Search tree?
A binary search tree follows some order to arrange the elements. In a Binary search
tree, the value of left node must be smaller than the parent node, and the value of
right node must be greater than the parent node. This rule is applied recursively to
the left and right subtrees of the root.

30
Let's understand the concept of Binary search tree with an example.

In the above figure, we can observe that the root node is 40, and all the nodes of the
left subtree are smaller than the root node, and all the nodes of the right subtree are
greater than the root node.

Similarly, we can see the left child of root node is greater than its left child and
smaller than its right child. So, it also satisfies the property of binary search tree.
Therefore, we can say that the tree in the above image is a binary search tree.

Suppose if we change the value of node 35 to 55 in the above tree, check whether
the tree will be binary search tree or not.

31
In the above tree, the value of root node is 40, which is greater than its left child 30
but smaller than right child of 30, i.e., 55. So, the above tree does not satisfy the
property of Binary search tree. Therefore, the above tree is not a binary search tree.

Example of creating a binary search tree


Now, let's see the creation of binary search tree using an example.

Suppose the data elements are - 45, 15, 79, 90, 10, 55, 12, 20, 50

o First, we have to insert 45 into the tree as the root of the tree.
o Then, read the next element; if it is smaller than the root node, insert it as the
root of the left subtree, and move to the next element.
o Otherwise, if the element is larger than the root node, then insert it as the root
of the right subtree.

Now, let's see the process of creating the Binary search tree using the given data
element. The process of creating the BST is shown below -

Step 1 - Insert 45.

Step 2 - Insert 15.

As 15 is smaller than 45, so insert it as the root node of the left subtree.

32
Step 3 - Insert 79.

As 79 is greater than 45, so insert it as the root node of the right subtree.

Step 4 - Insert 90.

90 is greater than 45 and 79, so it will be inserted as the right subtree of 79.

33
Step 5 - Insert 10.

10 is smaller than 45 and 15, so it will be inserted as a left subtree of 15.

Step 6 - Insert 55.

55 is larger than 45 and smaller than 79, so it will be inserted as the left subtree of
79.

Step 7 - Insert 12.

12 is smaller than 45 and 15 but greater than 10, so it will be inserted as the right
subtree of 10.

34
Step 8 - Insert 20.

20 is smaller than 45 but greater than 15, so it will be inserted as the right subtree of
15.

35
Step 9 - Insert 50.

50 is greater than 45 but smaller than 79 and 55. So, it will be inserted as a left
subtree of 55.

Now, the creation of binary search tree is completed. After that, let's move towards
the operations that can be performed on Binary search tree.

Balanced Binary Search Tree/ Balanced


Binary Tree:
 A balanced binary tree is also known as height balanced binary tree.
 It is defined as binary tree in when the difference between the height of the
left subtree and right subtree is not more than 1.
 The height of a tree is the number of edges on the longest path between the
root node and the leaf node.
 A Balanced Binary Tree will be a Balanced Binary Search Tree when it
fulfills the requirement of a binary search tree.

36
Following are the conditions for a height-balanced binary tree:

 difference between the left and the right subtree for any node is not more
than one
 the left subtree is balanced
 the right subtree is balanced

Example1 (Here we considered the example of Balanced Binary Search


Tree):

Now we will see whether the above tree is balanced or not. The left subtree contains
the nodes n2, n4, n5, and n7, while the right subtree contains the nodes n3 and n6.
The left subtree has two leaf nodes, i.e., n4 and n7. There is only one edge between
the node n2 and n4 and two edges between the nodes n7 and n2; therefore, node
n7 is the farthest from the root node. The height of the left subtree is 2(where n2 is
considered as root node, that is from n2 to n7). The right subtree contains only one
leaf node, i.e., n6, and has only one edge; therefore, the height of the right subtree is
1 (where n3 is considered as root node, that is from n3 to n6). The difference
between the heights of the left subtree and right subtree is 1. Since we got the value
1, so we can say that the above tree is a height-balanced tree. This process of
calculating the difference between the heights should be performed for each node
like n2, n3, n4, n5, n6 and n7. When we process each node, then we will find that the
value of k is not more than 1, so we can say that the above tree is a balanced binary
tree.

37
Example2 (Here we considered the example of Balanced Binary Search
Tree):

In the above tree, n6, n4, and n3 are the leaf nodes, where n6 is the farthest node
from the root node. Three edges exist between the root node and the leaf node;
therefore, the height of the above tree is 3. When we consider n1 as the root node,
then the left subtree contains the nodes n2, n4, n5, and n6, while subtree contains
the node n3. In the left subtree, n2 is a root node, and n4 and n6 are leaf nodes.
Among n4 and n6 nodes, n6 is the farthest node from its root node, and n6 has two
edges; therefore, the height of the left subtree is 2. The right subtree does have any
child on its left and right; therefore, the height of the right subtree is 0. Since the
height of the left subtree is 2 and the right subtree is 0, so the difference between
the height of the left subtree and right subtree is 2. According to the definition, the
difference between the height of left sub tree and the right subtree must not be
greater than 1. In this case, the difference comes to be 2, which is greater than 1;
therefore, the above binary tree is an unbalanced binary search tree.

38
AVL Tree:
An AVL tree can be defined as a self-balancing Binary Search Tree or Balanced
Binary Search Tree where the difference between heights of left and right subtrees
for any node can not be more than one.

The difference between the heights of the left subtree and right subtree for any
node is known as the balance factor of the node.

Tree is said to be balanced if balance factor of each node is in between -1 to 1,


otherwise, the tree will be unbalanced and need to be balanced.

Balance Factor (k) = height (left(k)) - height (right(k))


 If balance factor of any node is 1, it means that the left sub-tree is one level
higher than the right sub-tree.
 If balance factor of any node is 0, it means that the left sub-tree and right sub-
tree contain equal height.
 If balance factor of any node is -1, it means that the left sub-tree is one level
lower than the right sub-tree.

An AVL tree is given in the following figure. We can see that, balance factor
associated with each node is in between -1 and +1. therefore, it is an example of AVL
tree.

39
Time Complexity

Operations Best case time Average case time Worst case time
complexity complexity complexity

Insertion O(log n) O(log n) O(n)

Deletion O(log n) O(log n) O(n)

Search O(log n) O(log n) O(n)

40
Graph
A graph can be defined as group of vertices and edges that are used to connect
these vertices. A graph can be seen as a cyclic tree, where the vertices (Nodes)
maintain any complex relationship among them instead of having parent child
relationship.

Definition
A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of
vertices and E(G) represents the set of edges which are used to connect these
vertices.

A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B), (B,C), (C,E), (E,D),
(D,B), (D,A)) is shown in the following figure.

Directed and Undirected Graph


A graph can be directed or undirected. However, in an undirected graph, edges are
not associated with the directions with them. An undirected graph is shown in the
above figure since its edges are not attached with any of the directions. If an edge
exists between vertex A and B then the vertices can be traversed from B to A as well
as A to B.

41
In a directed graph, edges form an ordered pair. Edges represent a specific path
from some vertex A to another vertex B. Node A is called initial node while node B is
called terminal node.

A directed graph is shown in the following figure.

Graph Terminology
Path
A path can be defined as the sequence of nodes that are followed in order to reach
some terminal node V from the initial node U.

Closed Path
A path will be called as closed path if the initial node is same as terminal node. A
path will be closed path if V0=VN.

Simple Path
If all the nodes of the graph are distinct with an exception V 0=VN, then such path P is
called as closed simple path.

42
Complete Graph
A complete graph is the one in which every node is connected with all other nodes.
A complete graph contain n(n-1)/2 edges where n is the number of nodes in the
graph.

Weighted Graph
In a weighted graph, each edge is assigned with some data such as length or weight.
The weight of an edge e can be given as w(e) which must be a positive (+) value
indicating the cost of traversing the edge.

Adjacent Nodes
If two nodes u and v are connected via an edge e, then the nodes u and v are called
as neighbours or adjacent nodes.

Degree of the Node


A degree of a node is the number of edges that are connected with that node. A
node with degree 0 is called as isolated node.

Graph representation
A graph is a data structure that consist a sets of vertices (called nodes) and edges.
There are two ways to store Graphs into the computer's memory:

o Sequential representation (or, Adjacency matrix representation)


o Linked list representation (or, Adjacency list representation)

43
Sequential representation
Now, let's see the adjacency matrix representation of an undirected graph.

In the above figure, an image shows the mapping among the vertices (A, B, C, D, E),
and this mapping is represented by using the adjacency matrix.

There exist different adjacency matrices for the directed and undirected graph. In a
directed graph, an entry Aij will be 1 only when there is an edge directed from V i to
Vj.

Adjacency matrix for a directed graph


In a directed graph, edges represent a specific path from one vertex to another
vertex. Suppose a path exists from vertex A to another vertex B; it means that node A
is the initial node, while node B is the terminal node.

Consider the below-directed graph and try to construct the adjacency matrix of it.

44
In the above graph, we can see there is no self-loop, so the diagonal entries of the
adjacent matrix are 0.

Adjacency matrix for a weighted directed graph

It is similar to an adjacency matrix representation of a directed graph except that


instead of using the '1' for the existence of a path, here we have to use the weight
associated with the edge. The weights on the graph edges will be represented as the
entries of the adjacency matrix. We can understand it with the help of an example.
Consider the below graph and its adjacency matrix representation. In the
representation, we can see that the weight associated with the edges is represented
as the entries in the adjacency matrix.

45
In the above image, we can see that the adjacency matrix representation of the
weighted directed graph is different from other representations. It is because, in this
representation, the non-zero values are replaced by the actual weight assigned to
the edges.

Linked list representation


An adjacency list is used in the linked representation to store the Graph in the
computer's memory. It is efficient in terms of storage as we only have to store the
values for edges.

Let's see the adjacency list representation of an undirected graph.

In the above figure, we can see that there is a linked list or adjacency list for every
node of the graph. From vertex A, there are paths to vertex B and vertex D. These
nodes are linked to nodes A in the given adjacency list.

Now, consider the directed graph, and let's see the adjacency list representation of
that graph.

46
For a directed graph, the sum of the lengths of adjacency lists is equal to the number
of edges present in the graph.

Now, consider the weighted directed graph, and let's see the adjacency list
representation of that graph.

In the case of a weighted directed graph, each node contains an extra field that is
called the weight of the node.

47
BFS algorithm
In this article, we will discuss the BFS algorithm in the data structure. Breadth-first
search is a graph traversal algorithm that starts traversing the graph from the root
node and explores all the neighboring nodes. Then, it selects the nearest node and
explores all the unexplored nodes. While using BFS for traversal, any node in the
graph can be considered as the root node.

BFS puts every vertex of the graph into two categories - visited and non-visited. It
selects a single node in a graph and, after that, visits all the nodes adjacent to the
selected node.

Example of BFS algorithm


Now, let's understand the working of BFS algorithm by using an example. In the
example given below, there is a directed graph having 7 vertices.

In the above graph, minimum path 'P' can be found by using the BFS that will start
from Node A and end at Node E. The algorithm uses two queues, namely QUEUE1
and QUEUE2. QUEUE1 holds all the nodes that are to be processed, while QUEUE2
holds all the nodes that are processed and deleted from QUEUE1.

Now, let's start examining the graph starting from Node A.

Step 1 - First, add A to queue1 and NULL to queue2.

1. QUEUE1 = {A}
2. QUEUE2 = {NULL}

48
Step 2 - Now, delete node A from queue1 and add it into queue2. Insert all
neighbors of node A to queue1.

1. QUEUE1 = {B, D}
2. QUEUE2 = {A}

Step 3 - Now, delete node B from queue1 and add it into queue2. Insert all
neighbors of node B to queue1.

1. QUEUE1 = {D, C, F}
2. QUEUE2 = {A, B}

Step 4 - Now, delete node D from queue1 and add it into queue2. Insert all
neighbors of node D to queue1. The only neighbor of Node D is F since it is already
inserted, so it will not be inserted again.

1. QUEUE1 = {C, F}
2. QUEUE2 = {A, B, D}

Step 5 - Delete node C from queue1 and add it into queue2. Insert all neighbors of
node C to queue1.

1. QUEUE1 = {F, E, G}
2. QUEUE2 = {A, B, D, C}

Step 5 - Delete node F from queue1 and add it into queue2. Insert all neighbors of
node F to queue1. Since all the neighbors of node F are already present, we will not
insert them again.

1. QUEUE1 = {E, G}
2. QUEUE2 = {A, B, D, C, F}

Step 6 - Delete node E from queue1. Since all of its neighbors have already been
added, so we will not insert them again. Now, all the nodes are visited, and the
target node E is encountered into queue2.

1. QUEUE1 = {G}
2. QUEUE2 = {A, B, D, C, F, E}

49
Complexity of BFS algorithm
Time complexity of BFS depends upon the data structure used to represent the
graph. The time complexity of BFS algorithm is O(V+E), since in the worst case, BFS
algorithm explores every node and edge. In a graph, the number of vertices is O(V),
whereas the number of edges is O(E).

The space complexity of BFS can be expressed as O(V), where V is the number of
vertices.

50
DFS (Depth First Search) algorithm
It is a recursive algorithm to search all the vertices of a tree data structure or a graph.
The depth-first search (DFS) algorithm starts with the initial node of graph G and
goes deeper until we find the goal node or the node with no children.

Because of the recursive nature, stack data structure can be used to implement the
DFS algorithm. The process of implementing the DFS is similar to the BFS algorithm.

A standard DFS implementation puts each vertex of the graph into one of two
categories:

1. Visited
2. Not Visited.

The step by step process to implement the DFS traversal is given as follows -

1. First, create a stack with the total number of vertices in the graph.
2. Start by putting any one of the graph’s vertices on top of a stack.
3. Take the top item of the stack, print it and add it to the visited list.
4. Create a list of that vertex’s adjacent nodes. Add the ones which are not in the
visited list to the top of the stack.
5. Keep repeating steps 3 and 4 untill the stack is empty.

51
Example of DFS algorithm
Now, let's understand the working of the DFS algorithm by using an example. In the
example given below, there is a directed graph having 7 vertices.

Now, let's start examining the graph starting from Node H.

Step 1 - First, push H onto the stack.

1. STACK: H

Step 2 - POP the top element from the stack, i.e., H, and print it. Now, PUSH all the
neighbors of H onto the stack that are in ready state.

1. Print: H]STACK: A

Step 3 - POP the top element from the stack, i.e., A, and print it. Now, PUSH all the
neighbors of A onto the stack that are in ready state.

2. Print: A
3. STACK: B, D

Step 4 - POP the top element from the stack, i.e., D, and print it. Now, PUSH all the
neighbors of D onto the stack that are in ready state.

1. Print: D
2. STACK: B, F

52
Step 5 - POP the top element from the stack, i.e., F, and print it. Now, PUSH all the
neighbors of F onto the stack that are in ready state.

1. Print: F
2. STACK: B

Step 6 - POP the top element from the stack, i.e., B, and print it. Now, PUSH all the
neighbors of B onto the stack that are in ready state.

1. Print: B
2. STACK: C

Step 7 - POP the top element from the stack, i.e., C, and print it. Now, PUSH all the
neighbors of C onto the stack that are in ready state.

1. Print: C
2. STACK: E, G

Step 8 - POP the top element from the stack, i.e., G and PUSH all the neighbors of G
onto the stack that are in ready state.

1. Print: G
2. STACK: E

Step 9 - POP the top element from the stack, i.e., E and PUSH all the neighbors of E
onto the stack that are in ready state.

1. Print: E
2. STACK:

Now, all the graph nodes have been traversed, and the stack is empty.

53
Tree traversal (Inorder, Preorder an Postorder)
These methods are used for binary tree traversal. In this article, we will discuss
the tree traversal in the data structure. The term 'tree traversal' means traversing or
visiting each node of a tree. There is a single way to traverse the linear data structure
such as linked list, queue, and stack. Whereas, there are multiple ways to traverse a
tree that are listed as follows -

o Preorder traversal
o Inorder traversal
o Postorder traversal

We know that, binary tree contains three parts:

1. Root
2. Left Subtree
3. Right Subtree.

Some points to remember:

1. Pre-order traversal contains root element as first element in traverse list.


2. Post-order traversal contains root element as last in traverse list.
3. For Binary Search Tree, in-order traversal is a sorted list.
4. A unique binary tree can be only constructed if either pre-order or post-
order traversal list is provided with in-order traversal list.

Preorder traversal
Algorithm

Until all nodes of the tree are not visited


1. Step 1 - Visit the root node
2. Step 2 - Traverse the left subtree recursively.
3. Step 3 - Traverse the right subtree recursively.

54
Example

Now, let's see the example of the preorder traversal technique.

Now, start applying the preorder traversal on the above tree. First, we traverse the
root node A; after that, move to its left subtree B, which will also be traversed in
preorder.

So, for left subtree B, first, the root node B is traversed itself; after that, its left
subtree D is traversed. Since node D does not have any children, move to right
subtree E. As node E also does not have any children, the traversal of the left subtree
of root node A is completed.

Now, move towards the right subtree of root node A that is C. So, for right subtree
C, first the root node C has traversed itself; after that, its left subtree F is traversed.
Since node F does not have any children, move to the right subtree G. As node G
also does not have any children, traversal of the right subtree of root node A is
completed.

Therefore, all the nodes of the tree are traversed. So, the output of the preorder
traversal of the above tree is -

A→B→D→E→C→F→G

55
Postorder traversal
Algorithm

Until all nodes of the tree are not visited


1. Step 1 - Traverse the left subtree recursively.
2. Step 2 - Traverse the right subtree recursively.
3. Step 3 - Visit the root node.

Example

Now, let's see the example of the postorder traversal technique.

Now, start applying the postorder traversal on the above tree. First, we traverse the
left subtree B that will be traversed in postorder. After that, we will traverse the right
subtree C in postorder. And finally, the root node of the above tree, i.e., A, is
traversed.

So, for left subtree B, first, its left subtree D is traversed. Since node D does not have
any children, traverse the right subtree E. As node E also does not have any children,
move to the root node B. After traversing node B, the traversal of the left subtree of
root node A is completed.

56
Now, move towards the right subtree of root node A that is C. So, for right subtree
C, first its left subtree F is traversed. Since node F does not have any children,
traverse the right subtree G. As node G also does not have any children, therefore,
finally, the root node of the right subtree, i.e., C, is traversed. The traversal of the
right subtree of root node A is completed.

At last, traverse the root node of a given tree, i.e., A. After traversing the root node,
the postorder traversal of the given tree is completed.

Therefore, all the nodes of the tree are traversed. So, the output of the postorder
traversal of the above tree is -

D→E→B→F→G→C→A

Inorder traversal
Algorithm

Until all nodes of the tree are not visited


1. Step 1 - Traverse the left subtree recursively.
2. Step 2 - Visit the root node.
3. Step 3 - Traverse the right subtree recursively.

57
Example

Now, let's see the example of the Inorder traversal technique.

Now, start applying the inorder traversal on the above tree. First, we traverse the left
subtree B that will be traversed in inorder. After that, we will traverse the root
node A. And finally, the right subtree C is traversed in inorder.

So, for left subtree B, first, its left subtree D is traversed. Since node D does not have
any children, so after traversing it, node B will be traversed, and at last, right subtree
of node B, that is E, is traversed. Node E also does not have any children; therefore,
the traversal of the left subtree of root node A is completed.

After that, traverse the root node of a given tree, i.e., A.

At last, move towards the right subtree of root node A that is C. So, for right subtree
C; first, its left subtree F is traversed. Since node F does not have any children,
node C will be traversed, and at last, a right subtree of node C, that is, G, is traversed.
Node G also does not have any children; therefore, the traversal of the right subtree
of root node A is completed.

As all the nodes of the tree are traversed, the inorder traversal of the given tree is
completed. The output of the inorder traversal of the above tree is -

D→B→E→A→F→C→G

58
Differences between tree and graph data structure

Tree Graph

It is a collection of edges and nodes. It is a collection of vertices and


edges.

In tree data structure, there is a unique In graph data structure, there is no


node known as a parent node. unique node.

It does not create any loop or cycle. In graph, loop or cycle can be
formed.

It is a hierarchical model because nodes It is a network model. For example,


are arranged in multiple level, and that facebook is a social network that
creates a hierarchy. For example, any uses the graph data structure.
organization will have a hierarchical
model.

If there are n nodes then there would The number of edges depends on
be n-1 number of edges. the graph.

Tree data structure will always have In graph data structure, all the edges
directed edges. can either be directed edges,
undirected edges, or both.

It is used for inserting, deleting or It is mainly used for finding the


searching any element in tree. shortest path in the network.

59
Differences between BFS and DFS
The following are the differences between the BFS and DFS:

BFS DFS

BFS stands for Breadth First Search. DFS stands for Depth First Search.

Queue data structure is used for the Stack data structure is used for the
BFS traversal. DFS traversal.

BFS does not use the backtracking DFS uses backtracking to traverse all
concept. the unvisited nodes.

BFS is slower than DFS. DFS is faster than BFS.

It is not memory efficient as it requires It is memory efficient as it requires


more memory than DFS. less memory than BFS.

60
Polish Notation:
Polish notation is a notation form for expressing arithmetic, logic and
algebraic equations

What is infix notation?


When the operator is written in between the operands, then it is known
as infix notation.

For example,

A*(B+C)/D

Syntax of infix notation is given below:

<operand> <operator> <operand>

Operator Precedence:

The order of the operator precedence is given in the below table:

Operators Symbols

Parenthesis ( ), {}, [ ]

Exponents ^

Multiplication and Division *, /

Addition and Subtraction +,-

The first preference is given to the parenthesis; then next preference is given
to the exponents. In the case of multiple exponent operators, then the
operation will be applied from right to left. In other cases, the operation will
be applied from left to right.
61
For example:

2^2^3 = 2 ^ 8

= 256

After exponent, multiplication, and division operators are evaluated. If both


the operators are present in the expression, then the operation will be applied
from left to right.

The next preference is given to addition and subtraction. If both the operators
are available in the expression, then we go from left to right.

The operators that have the same precedence termed as operator


associativity. If we go from left to right, then it is known as left-associative. If
we go from right to left, then it is known as right-associative.

Postfix Expression
The postfix expression is an expression in which the operator is written after
the operands. For example, the postfix expression of infix notation ( 2+3) can
be written as 23+. Postfix notation is also called Reverse polish notation.

Some key points regarding the postfix expression are:

o In postfix expression, operations are performed in the order in which


they have written from left to right.
o It does not any require any parenthesis.
o We do not need to apply operator precedence rules and associativity
rules.

62
Let's understand the above algorithm through an example.

Infix expression: 2 + 3 * 4

We will start scanning from the left most of the expression. The multiplication
operator is an operator that appears first while scanning from left to right.
Now, the expression would be:

Expression = 2 + 34*

= 2 + 12

Again, we will scan from left to right, and the expression would be:

Expression = 2 12 +

= 14

Evaluation of postfix expression using stack. /


Algorithm to evaluate postfix expression

o Scan the expression from left to right.


o If we encounter any operand in the expression, then we push the
operand in the stack.
o When we encounter any operator in the expression, then we pop the
corresponding operands from the stack.
o When we finish with the scanning of the expression, the final value
remains in the stack.

63
Let's understand the evaluation of postfix expression using stack.

Example 1: Postfix expression: 2 3 4 * +

Input Stack

234* empty Push 2


+

3 4 * 2 Push 3
+

4*+ 32 Push 4

*+ 432 Pop 4 and 3, and perform 4*3 = 12. Push 12 into the
stack.

+ 12 2 Pop 12 and 2 from the stack, and perform 12+2 = 14.


Push 14 into the stack.

The result of the above expression is 14.

Example 2: Postfix expression: 3 4 * 2 5 * +

Input Stack

34*25 empty Push 3


*+

4*25* 3 Push 4
+

*2 5 * + 43 Pop 3 and 4 from the stack and perform 3*4 = 12. Push
12 into the stack.

64
25*+ 12 Push 2

5*+ 2 12 Push 5

*+ 5 2 12 Pop 5 and 2 from the stack and perform 5*2 = 10. Push
10 into the stack.

+ 10 12 Pop 10 and 12 from the stack and perform 10+12 = 22.


Push 22 into the stack.

The result of the above expression is 22.

Conversion of infix to postfix


Here, we will use the stack data structure for the conversion of infix expression
to prefix expression. Whenever an operator will encounter, we push operator
into the stack. If we encounter an operand, then we append the operand to
the expression.

Rules for the conversion from infix to postfix expression

1. Print the operand as they arrive.


2. If the stack is empty or contains a left parenthesis on top, push the
incoming operator on to the stack.
3. If the incoming symbol is '(', push it on to the stack.
4. If the incoming symbol is ')', pop the stack and print the operators until
the left parenthesis is found.
5. If the incoming symbol has higher precedence than the top of the stack,
push it on the stack.

65
6. If the incoming symbol has lower precedence than the top of the stack,
pop and print the top of the stack. Then test the incoming operator
against the new top of the stack.
7. If the incoming operator has the same precedence with the top of the
stack then use the associativity rules. If the associativity is from left to
right then pop and print the top of the stack then push the incoming
operator. If the associativity is from right to left then push the incoming
operator.
8. At the end of the expression, pop and print all the operators of the
stack.

Let's understand through an example.

Infix expression: K + L - M*N + (O^P) * W/U/V * T + Q

Input Expression Stack Postfix Expression

K K

+ +

L + KL

- - K L+

M - K L+ M

* -* K L+ M

N -* KL+MN

66
+ + K L + M N*
K L + M N* -

( +( K L + M N *-

O +( KL+MN*-O

^ +(^ K L + M N* - O

P +(^ K L + M N* - O P

) + K L + M N* - O P ^

* +* K L + M N* - O P ^

W +* K L + M N* - O P ^ W

/ +/ K L + M N* - O P ^ W *

U +/ K L + M N* - O P ^W*U

/ +/ K L + M N* - O P ^W*U/

V +/ KL + MN*-OP^W*U/V

* +* KL+MN*-OP^W*U/V/

T +* KL+MN*-OP^W*U/V/T

+ + KL+MN*-OP^W*U/V/T*
KL+MN*-OP^W*U/V/T*+

Q + KL+MN*-OP^W*U/V/T*Q

KL+MN*-OP^W*U/V/T*+Q+

67
The final postfix expression of infix expression(K + L - M*N + (O^P) * W/U/V *
T + Q) is KL+MN*-OP^W*U/V/T*+Q+.

What is Prefix notation?


A prefix notation is another form of expression but it does not require other
information such as precedence and associativity, whereas an infix notation
requires information of precedence and associativity. It is also known as polish
notation. In prefix notation, an operator comes before the operands. The
syntax of prefix notation is given below:

<operator> <operand> <operand>

For example, if the infix expression is 5+1, then the prefix expression
corresponding to this infix expression is +51.

If the infix expression is:

a*b+c

*ab+c

+*abc (Prefix expression)

Consider another example:

A+B*C

First scan: In the above expression, multiplication operator has a higher


precedence than the addition operator; the prefix notation of B*C would be
(*BC).

A + *BC
68
Second scan: In the second scan, the prefix would be:

+A *BC

In the above expression, we use two scans to convert infix to prefix expression.
If the expression is complex, then we require a greater number of scans. We
need to use that method that requires only one scan, and provides the desired
result. If we achieve the desired output through one scan, then the algorithm
would be efficient. This is possible only by using a stack.

69
Evaluation of Prefix Expression using Stack:

Let's understand the evaluation of prefix expression through an example.

Expression: +, -, *, 2, 2, /, 16, 8, 5

First, we will reverse the expression given above.

Expression: 5, 8, 16, /, 2, 2, *, -, +

We will use the stack data structure to evaluate the prefix expression.

Symbol Scanned Stack

5 5

8 5, 8

16 5, 8, 16

/ 5, 2

2 5, 2, 2

2 5, 2, 2, 2

* 5, 2, 4

- 5, 2

+ 7

The final result of the above expression is 7.

70
Conversion of Prefix to Postfix Expression
Here, we will see the conversion of prefix to postfix expression using a stack
data structure.

Rules for prefix to postfix expression using stack data structure:

o Scan the prefix expression from right to left, i.e., reverse.


o If the incoming symbol is an operand then push it into the stack.
o If the incoming symbol is an operator then pop two operands from the
stack. Once the operands are popped out from the stack, we add the
incoming symbol after the operands. When the operator is added after
the operands, then the expression is pushed back into the stack.
o Once the whole expression is scanned, pop and print the postfix
expression from the stack.

71
Let's understand the conversion of Prefix to Postfix expression using
Stack through an example.

If the expression is: * - A / B C - / A K L

Symbols Action Stack Description


to be
scanned

L Push L into the L


stack

K Push K into the L, K


stack

A Push A into the L, K, A


stack

/ Pop A from the L, A K / Pop two operands from the


stack stack, i.e., A and K. Add '/'
Pop K from the operator after K operand, i.e.,
stack AK/. Push AK/ into the stack.
Push A K / into the
stack

- Pop A K / and L A K / L Pop two operands from the


from the stack. - stack, i.e., AK/ and L. Add '-'
Push (A K / L -) into operator after 'L' operand.
the stack

C Push C into the AK/L-,


stack C

B Push B into the AK/L-,


stack C, B

72
/ Pop B and C from AK/L-, Pop two operands from the
the stack. BC/ stack, i.e., B and C. Add '/'
Push BC/ into the operator after C operator, i.e.,
stack. BC/. Push BC/ into the stack.

A Push A into the AK/L-,


stack BC/, A

- Pop BC/ and A from AK/L-, Pop two operands from the
the stack. Push ABC/- stack, i.e., A and BC/. Add '-'
ABC/- into the operator after '/'.
stack.

* Pop ABC/- and ABC/- Pop two operands from the


AK/L- from the AK/L-* stack, i.e., ABC/-, and AK/L- .
stack. Push Add '*' operator after L and '-'
ABC/AK/L-* into the operator, i.e., ABC/-AK/L-*.
stack.

73
Conversion of Postfix to Prefix expression using Stack
The following are the steps used to convert postfix to prefix expression using
stack:

o Scan the postfix expression from left to right.


o If the element is an operand, then push it into the stack.
o If the element is an operator, then pop two operands from the stack.

Create an expression by concatenating two operands and adding operator


before the operands.

Push the result back to the stack.

o Repeat the above steps until we reach the end of the postfix expression

Let's understand the conversion of postfix to prefix expression using


stack.

If the Postfix expression is given as:

AB + CD - *

Symbol Action Stack Description


Scanned

A Push A into A
the stack

B Push B into AB
the stack

+ Pop B from +AB Pop two operands from the stack, i.e., A
the stack and B. Add '+' operator before the

74
Pop A from operands AB, i.e., +AB.
the stack
Push +AB
into the
stack.

C Push C into +ABC


the stack

D Push D into +ABCD


the stack

- Pop D from +AB - Pop two operands from the stack, i.e., D
the stack. CD and C. Add '-' operator before the
Pop C from operands CD, i.e., -CD.
the stack.
Push -CD
into the
stack

* Pop -CD *+AB - Pop two operands from the stack, i.e., -
from the CD CD and +AB. Add '*' operator before
stack. +AB then the expression would become
Pop +AB *+AB-CD.
from the
stack.
Push *+AB -
CD into the
stack.

The prefix expression of the above postfix expression is *+AB-CD.

75
Some problems and solutions of polish and reverse
polish notation:
Question 1: Convert the infix expression (A + B) × (C + D)
into Prefix or Polish notation?

Solution:

(A + B) × (C + D)

= [+ AB] × [+ CD]

= × [+ AB + CD]

= × + AB + CD

So, the Polish notation of (A + B) × (C + D) is × + AB + CD.

76
Question 2: Convert the infix expression A × B + A × (B × D
+ C × E) into Polish notation?

Solution:

A × B + A × (B × D + C × E)

= A × B + A × ([× BD] + [× CE])

= A × B + A × [+ × BD × CE]

= A × B + [× A + × BD × CE]

= [× AB] + [× A + × BD × CE]

= [+ × AB × A + × BD × CE]

= + × AB × A + × BD × CE

So, the Polish notation of A × B + A × (B × D + C × E) is + × AB


× A + × BD × CE.

77
Question 3: Convert the infix expression A × {B + C × (D +
E)} / F × (G + H) into prefix notation?

Solution:

A × {B + C × (D + E)} / F × (G + H)

= A × {B + C × [+ DE]} / F × [+GH]

= A × {B + [× C + DE]} / [× F + GH]

= A × [+ B × C + DE] / [× F + GH]

= [× A + B × C + DE] / [× F + GH]

= / × A + B × C + DE × F + GH

So, the Polish notation of A × {B + C × (D + E)} / F × (G + H) is /


× A + B × C + DE × F + GH.

78
Question 4: Evaluate the prefix expression or polish
expression × 5 – 4 3 using stack?

Solution: Inserting the symbol # at the left end of the


expression. Now the expression becomes # × 5 – 4 3.

Prefix Expression Symbol Scanned Stack


#×5–43 None Empty
#×5–4 3 3
#×5– 4 3, 4
#×5 – 4–3=1
#× 5 1, 5
# × 5×1=5
# Result = 5

79
Question 5: Evaluate the Polish expression -+-x43250/x784
using stack?

Solution: Put symbol # at the left end of the expression.

Polish Expression: # – + – × 4 3 2 50 / × 7 8 4

Prefix expression Symbol scanned Stack


# – + – × 4 3 2 50 / × 7 8 4 None Empty
# – + – × 4 3 2 50 / × 7 8 4 4
# – + – × 4 3 2 50 / × 7 8 4, 8
# – + – × 4 3 2 50 / × 7 4, 8, 7
# – + – × 4 3 2 50 / × 4, 56 (8 × 7 = 56)
# – + – × 4 3 2 50 / 14 (56 / 4 = 14)
#–+–×432 50 14, 50
#–+–×43 2 14, 50, 2
#–+–×4 3 14, 50, 2, 3
#–+–× 4 14, 50, 2, 3, 4
#–+– × 14, 50, 2, 12 (4 × 3 = 12)
#–+ – 14, 50, 10 (12 – 2 = 10)
#– + 14, 60 (50 + 10 = 60)
# – 46 (60 – 14 = 46)
# Result = 46

80
Question 6: Convert the infix notation A × B + C × D + E × F
into Postfix Notation or Reverse Polish Notation?

Solution:

A×B+C×D+E×F

= [AB ×] + [CD ×] + [EF ×]

= [AB × CD × +] + [EF ×]

= [AB × CD × + EF × +]

= AB × CD × + EF × +

So the postfix notation or reverse polish notation of (A × B + C


× D + E × F) is AB × CD × + EF × +.

81
Question 7: Convert the infix notation {A – B + C × (D × E –
F)} / G + H × K into postfix notation?

Solution:

{A – B + C × (D × E – F)} / G + H × K

= {A – B + C × ([DE ×] – F)} / G + [HK ×]

= {A – B + C × [DE × F –]} / [G HK × +]

= {A – B + [C DE × F – ×]} / [G HK × +]

= {[AB –] + [C DE × F – ×]} / [G HK × +]

= [AB – C DE × F – × +] / [G HK × +]

= [AB – C DE × F – × + G HK × + /]

= AB – C DE × F – × + G HK × + /

So the reverse polish notation is AB – C DE × F – × + G HK × +


/.

82
Question 8: Evaluate the post fix expression or reverse
polish expression 50 4 3 × 2 – + 7 8 × 4 / – using stack?

Solution: Put symbol # at the right end of the expression.

Postfix Expression: 50 4 3 × 2 – + 7 8 × 4 / – #

Postfix expression Symbol scanned Stack


50 4 3 × 2 – + 7 8 × 4 / – # None Empty
43×2–+78×4/–# 50 50
3×2–+78×4/–# 4 50, 4
×2–+78×4/–# 3 50, 4, 3
2–+78×4/–# × 50, 12 (4 × 3 = 12)
–+78×4/–# 2 50, 12, 2
+78×4/–# – 50, 10 (12 – 2 = 10)
78×4/–# + 60 (50 + 10 = 60)
8×4/–# 7 60, 7
×4/–# 8 60, 7, 8
4/–# × 60, 56 (7 × 8 = 56)
/–# 4 60, 56, 4
–# / 60, 14 (56 / 4 = 14)
# – 46 (60 – 14 = 46)
_ # Result = 46

83
Difference between Polish Notation and Reverse Polish Notation:

After reading this note please have a look into Colud It book.
It won’t take so much time. Some topics are in the book.

84

You might also like