Data Structures
Data Structures
The Data Structure is the way data is organized (stored) and manipulated for
retrieval and access.
Can you explain the difference between file structure and storage
structure?
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.
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.
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.
3
Working of Stack Data Structure
The operations work as follows:
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:
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.
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.
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:
Enqueue Operation
Dequeue Operation
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
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 -
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.
13
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()
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
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.
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.
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.
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.
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
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.
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.
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.
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
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.
2. 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.
28
Let's look at the simple example of the Full 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.
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.
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 -
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.
90 is greater than 45 and 79, so it will be inserted as the right subtree of 79.
33
Step 5 - Insert 10.
55 is larger than 45 and smaller than 79, so it will be inserted as the left subtree of
79.
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.
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
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.
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
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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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
1. Root
2. Left Subtree
3. Right Subtree.
Preorder traversal
Algorithm
54
Example
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
Example
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
57
Example
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.
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 does not create any loop or cycle. In graph, loop or cycle can be
formed.
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.
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.
60
Polish Notation:
Polish notation is a notation form for expressing arithmetic, logic and
algebraic equations
For example,
A*(B+C)/D
Operator Precedence:
Operators Symbols
Parenthesis ( ), {}, [ ]
Exponents ^
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
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.
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.
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
63
Let's understand the evaluation of postfix expression using stack.
Input Stack
3 4 * 2 Push 3
+
4*+ 32 Push 4
*+ 432 Pop 4 and 3, and perform 4*3 = 12. Push 12 into the
stack.
Input Stack
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.
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.
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+.
For example, if the infix expression is 5+1, then the prefix expression
corresponding to this infix expression is +51.
a*b+c
*ab+c
A+B*C
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:
Expression: +, -, *, 2, 2, /, 16, 8, 5
Expression: 5, 8, 16, /, 2, 2, *, -, +
We will use the stack data structure to evaluate the prefix expression.
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
70
Conversion of Prefix to Postfix Expression
Here, we will see the conversion of prefix to postfix expression using a stack
data structure.
71
Let's understand the conversion of Prefix to Postfix expression using
Stack through an example.
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.
- 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.
73
Conversion of Postfix to Prefix expression using Stack
The following are the steps used to convert postfix to prefix expression using
stack:
o Repeat the above steps until we reach the end of the postfix expression
AB + CD - *
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.
- 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.
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
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]
= [× AB] + [× A + × BD × CE]
= [+ × AB × A + × BD × CE]
= + × 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
78
Question 4: Evaluate the prefix expression or polish
expression × 5 – 4 3 using stack?
79
Question 5: Evaluate the Polish expression -+-x43250/x784
using stack?
Polish Expression: # – + – × 4 3 2 50 / × 7 8 4
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 × +
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 × +]
= {[AB –] + [C DE × F – ×]} / [G HK × +]
= [AB – C DE × F – × +] / [G HK × +]
= [AB – C DE × F – × + G HK × + /]
= 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?
Postfix Expression: 50 4 3 × 2 – + 7 8 × 4 / – #
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