Kalinga Institute of Industrial Technology School of Computer Engineering
Kalinga Institute of Industrial Technology School of Computer Engineering
Strictly for internal circulation (within KIIT) and reference only. Not for outside circulation without permission
One of the disadvantages of using an array or linked list to store data is the time necessary to search for an
item. Since both the arrays and Linked Lists are linear structures the time required to search a “linear” list is
proportional to the size of the data set. For example, if the size of the data set is n, then the number of
comparisons needed to find (or not find) an item may be as bad as n. So imagine doing the search on a linked list
(or array) with n = 106 nodes. Even on a machine that can do million comparisons per second, searching for m
items will take roughly m seconds. This not acceptable in today’s world where speed at which we complete
operations is extremely important. Time is money. Therefore it seems that better (more efficient) data
structures are needed to store and search data.
In this chapter, we can extend the concept of linked data structure (linked list, stack, queue) to a structure that
may have multiple relations among its nodes. Such a structure is called atree. A tree is a nonlinear data
structure, compared to arrays, linked lists, stacks and queues which are linear data structures.
Become Rich
leaves
branches
root
root
leaves
branches
nodes
❑ A tree is a finite
nonempty set of nodes
and edges without
having any cycle.
❑ It is an abstract model
of a hierarchical
structure.
❑ Nodes represents the
parent-child relation.
A Sr # Property Value
1 Number of nodes of the tree
2 Height of the tree
B C 3 Root Node of the tree
4 Leaves of the tree
5 Interior nodes of the tree
6 Ancestors of H node
D E F 7 Descendants of B node
8 Siblings of E node
9 Right subtree of A node
10 Degree of the tree
G 11 Parent node of D
12 Child nodes of G
13 Level of node G
H I
Data
Tree is a fundamentally hierarchical structure. Thus, a tree is appropriate to model any reality that
exhibits hierarchy:
❑ File system directories.
❑ Genealogical trees of all sorts: family relationships among individuals, tribes, languages etc.
❑ Classifications systems:
❑ Taxonomic classification of plants and animals.
❑ Dewey decimal (or Library of Congress) classification of books.
❑ Breakdown of a manufactured product into subassemblies, each of turn consists of
sub-subassemblies etc. down to the smallest components.
❑ Structure of a program - main routine is the root, procedures it contains are subtrees, each of
which contains nested procedure definitions etc.
❑ Information storage and retrieval situations such as symbol tables, even though hierarchy may
not be involved.
❑ Expression Tress – Compilers and Interpreters as well in symbolic mathematics program to
represent arithmetic expressions.
❑ Game Tree – Game playing
A binary tree T is defined as a finite set of elements called node such that :
So - a binary tree is a tree data structure in which each node has at most two children
(i.e. either 0 or 1 or 2), which are referred to as the left child and the right child.
If T contains a root R, then the two trees T1 and T2 are called the left and right subtree
of R. If T1 is non empty then its root is called the left successor of R. Similarly if T2 is
not empty then its root is called the right successor of R.
T1 T2
Similar Tree
Trees Copies
Binary trees are said to be The trees are said to be
similar if they have the copies if they are similar
same structure or in other and if they have same
words, if they have the contents at corresponding
same shape. nodes
((3+4)*(1-2))
3 + ((5+9)*2)
Full but not Complete Complete but not Full Full and Complete Neither Full nor Complete
Let T be the binary tree. There are 2 ways of representing binary tree in memory.
The first and usual way is called the link representation of T and the second
way which uses a single array called the sequential representation of T.
Sequential
Representation
Binary Trees can be represented using 1-D array in memory. The rule to store
binary tree in array are :
tree
Approach 1 - Parallel
Array
Consider a binary tree T. The linked representation uses three parallel arrays i.e.
INFO,LEFT & RIGHT & a pointer variable ROOT. Each node N of T will correspond
to a location K such that:
If any subtree is empty, then the corresponding pointer will contain NULL values;
if the tree T itself is empty, then ROOT will contain NULL
Approach 2 - Nodes
Binary trees can be represented by links where each node contains the address of
the left child and the right child. If any node has its left or right child empty then
it will have in its respective link field, a null value. A leaf node has null value in
both of its links.
Node
Structure
Illustratio
n
A tree node should look like the below structure. It has data part and references to its left and right
child nodes.
struct node
{
struct node *leftChild;
int data;
struct node *rightChild;
} *root;
Basic operations that can be performed on binary search tree data structure, are −
❑ Insert − insert a node in a tree / create a tree.
❑ Search − search an element in a tree.
❑ Delete – Delete the tree or delete a node in the tree.
❑ Preorder Traversal − traverse a tree in a preorder manner.
❑ Inorder Traversal − traverse a tree in an inorder manner.
❑ Postorder Traversal − traverse a tree in a postorder manner.
Traversal is a process to visit all the nodes of a tree and may print their values
too. Because, all nodes are connected via edges, traverse always start from the
root node and one cannot random access a node in tree. There are three ways to
traverse a tree −
❑ In-order Traversal
❑ Pre-order Traversal
❑ Post-order Traversal
In this traversal method, the left-subtree is visited first, then root and then the
right sub-tree.
Recursive Algorithm
Step 1 − Start
Step 2 − Repeat steps 3, 4 and 5 until all nodes
are traversed
Step 3 − Recursively traverse left subtree
Step 4 − Visit root node
Step 5 − Recursively traverse right subtree
Step 6 − Stop
Output
Traversal start from A, and following in-order traversal, we move to its left subtree B. B is also traversed
in-ordered and the process goes on until all the nodes are visited. The output of in-order traversal of this tree is
D→B→E→A→F→C→G
In this traversal method, the root node is visited first, then left subtree and finally
right sub-tree.
Recursive Algorithm
Step 1 − Start
Step 2 − Repeat steps 3, 4 and 5 until all nodes
are traversed
Step 3 − Visit root node
Step 4 − Recursively traverse left subtree
Step 5 − Recursively traverse right subtree
Step 6 − Stop
Output
Traversal start from A, and following pre-order traversal, we first visit A itself and then move to its left
subtree B. B is also traversed pre-ordered. And the process goes on until all the nodes are visited. The
output of pre-order traversal of this tree is A → B → D → E → C → F → G
In this traversal method, the root node is visited last, hence the name. First the
left subtree is traversed, then right subtree and finally root.
Recursive Algorithm
Step 1 − Start
Step 2 − Repeat steps 3, 4 and 5 until all nodes
are traversed
Step 3 − Recursively traverse left subtree
Step 4 − Recursively traverse right subtree
Step 5 − Visit root node
Step 6 − Stop
Output
Traversal start from A, and following pre-order traversal, we first visit left subtree B. B is also traversed
post-ordered. And the process goes on until all the nodes are visited. The output of post-order traversal
of this tree is D → E → B → F → G → C → A
In this traversal method, visit the nodes level by level from left to right
Recursive Algorithm
Step 1 − Start
Step 2 − Visit the root node (Level 0)
Step 3 − Visit the root’s left child followed by
right child (Level 1)
Step 4 − Recursively visit the next levels from left
most child to right most child (Level 2 and
onwards) until all levels are covered
Step 5 − Stop
Output 10 → 12 → 23 → 14 → 15 → 16 → 27 →
28
School of Computer Engineering
Class Work
33
What are the In Order, Pre Order and Post Order traversal sequence of following trees?
In Order : B → D → A → G → E → C → H → F → I In Order : a → b → c → d → e → f → g → h → i → j → k
Pre Order : A → B → D → C → E → G → F → H Pre Order : f → b → a → d → c → e → i → h → g → k → j
→I
Post Order : a → c → e → d → b → g → h → j → k → i → f
Post Order : D → B → G → E → H → I → F → C
→Note
A
In Order : LPR Pre Order : PLR Post Order : LRP
1. Create a stack.
2. Push the root into the stack and set the root = root.left and continue till it hits NULL.
3. If root is null and stack is empty then
return // we are done.
Else
pop the top node from the stack and set it as, root = popped_node.
print the root and go right, root = root.right.
Go to step 2.
4. End If
Animation
http://algorithms.tutorialhorizon.com/files/2015/12/Inorder1.gif
Class Work
❑ Design non-recursive algorithm for Pre-order Traversal
❑ Design non-recursive algorithm for Post-order Traversal
School of Computer Engineering
Class Work – Construction of Binary Tree
35
In Order : B → D → A → G → E → C → H → F → I
36
37
38
39
40
A threaded binary tree is a binary tree in which the nodes that don’t have a
right child, have a thread to their inorder successor. The idea of threaded
binary trees is to make inorder traversal faster and do it without stack and
without recursion.
A binary search tree (BST) is a tree in which all nodes follows the below mentioned
properties −
❑ The left sub-tree of a node has data less than to its parent node's data.
❑ The right sub-tree of a node has data greater than to its parent node's data.
Thus, a BST divides all its sub-trees into two segments; left sub-tree and right sub-tree and
can be defined as - left_subtree (data) < node (data) < right_subtree (data)
if tree is empty
create a root node with the new key
else
compare key with the top node
if key = node key
replace the node with the new value
else if key > node key
compare key with the right subtree:
if subtree is empty create a leaf node
else add key in right subtree
else key < node key
compare key with the left subtree:
if the subtree is empty create a leaf node
else add key to the left subtree
else if the key value in the node is greater than the target
return the result of searching the left subtree
else if the key value in the node is smaller than the target
return the result of searching the right subtree
School of Computer Engineering
BST– Search - C Function
48
/* return a pointer to the node that contains key. If there is no such node, return NULL */
node* search(node * root, int key)
{
if (!root)
{
return NULL;
}
if (key == root->key)
{
return root;
}
Minimum Maximum
Key searchMinimum(node * root)
node* Key searchMaximum(node * root)
node*
{ {
if (!root) if (!root)
{ {
return NULL; return NULL;
} }
while (root -> left != NULL) while (root -> right != NULL)
{ {
root = root -> left; root = root -> right;
} }
Experimenting the
❑cases
if the tree is empty return false
❑ else attempt to locate the node containing the target using the binary search
algorithm:
❑ if the target is not found return false
❑ else the target is found, then remove its node & return true. Now while
removing the node four cases may happen
❑ Case 1 - if the node has 2 empty subtrees
❑ Case 2 - if the node has a left and a right subtree
❑ Case 3 - if the node has no left child
❑ Case 4 - if the node has no right child
Z
5 9 5 9
4 6 8 10 6 8 10
4 6 8 10 4 8 10
Z
7 7
5 9 6 9
6 8 10 8 10
5 9 9
4
4 8 10 8 10
4
4
5
2 6
6
7 1 3 5 7
School of Computer Engineering
How to check a Binary Tree is balanced or not?
58
❑ If at any given node, absolute difference of height of left sub-tree and height of right
sub-tree (called as balance factor) is not greater than 1 (i.e. should be -1 or 1 or 0)
Balance Unbalance
d d
It is observed that BST's worst-case performance closes to linear search algorithms, that is Ο(n). In real time
data we cannot predict data pattern and their frequencies. So a need arises to balance out existing BST. Named
after their inventor Adelson, Velski & Landis, AVL trees are height balancing binary search tree. AVL tree
checks the height of left and right sub-trees and assures that the difference is not more than 1. This difference is
called Balance Factor. Balance Factor = height(left-subtree) − height(right-subtree)
If the difference in the height of left and right sub-trees is more than 1, the
tree is balanced using rotation techniques.
To make itself balanced, an AVL tree may perform four kinds of rotations −
❑ Left rotation
❑ Right rotation
❑ Left-Right rotation
❑ Right-Left rotation
First two rotations are single rotations and next two rotations are double
rotations.
If a tree become unbalanced, when a node is inserted into the right subtree
of right subtree, then we perform single left rotation −
AVL tree may become unbalanced if a node is inserted in the left subtree of
left subtree. The tree then needs a right rotation.
As depicted, the unbalanced node becomes right child of its left child by
performing a right rotation.
State Action
State Action
Insertio Deletio
n n
❑ After inserting a node, check each ❑ If a node is a leaf, remove it.
of the node's ancestors for ❑ If the node is not a leaf, replace it
consistency with the AVL rules. with either the largest in its left
❑ For each node checked, if the subtree (i.e. the rightmost) or the
balance factor remains 1, 0, or -1 smallest in its right subtree (i.e.
then no rotations are necessary. the leftmost), and remove that
Otherwise, it's unbalanced. node.
❑ After each insertion, at most two ❑ After deletion, retrace the path
tree rotations are needed to from parent of the replacement to
restore the entire tree. the root, adjusting the balance
factors as needed.
t 3 th 2
e a wi
lanc tion
ba ota
Im R
orm
f
Per
Imbalance at 5
Perform Rotation with
8
School of Computer Engineering
AVL Tree Insertion and Deletion Simulation
70
https://www.cs.usfca.edu/~galles/visualization/AVLtree.htm
l
Searching for a key in an m-way search tree is similar to that of binary search tree
52
K : Key K
Ai , Aj : Pointers to sub-tree Ai Aj
Deletion Cases
[1] If (Ai = Aj = NULL) then delete K
[2] If (Ai ≠ NULL, Aj = NULL ) then choose the largest of the key elements K’ in
the child node pointed to by Ai and replace K by K’.
[3] If (Ai = NULL, Aj ≠ NULL ) then choose the smallest of the key element K”
from the subtree pointed to by Aj , delete K” and replace K by K”.
[4] If (Ai ≠ NULL, Aj ≠ NULL ) then choose the largest of the key elements K’ in
the subtree pointed to by Ai or the smallest of the key element K” from the
subtree pointed to by Aj to replace K.
Ai = Aj = NULL
Delete 151 18 44 76 198
X X
80 92 141 262
7 12
X X X
X X
Action : delete K X X X X
Ai = Aj = NULL
18 44 76 198
Post to the
X X Deletion of 151
80 92 141 262
7 12
X X X
X X
Ai = NULL, Aj ≠ NULL
Delete 262 18 44 76 198
X X
80 92 141 262
7 12
X X X
X X
Action : choose the largest of the key elements K’ 272 286 350
in the child node pointed to by Ai and replace K X X X X
by K’.
School of Computer Engineering
Deletion Case – 2 Result
81
Ai = NULL, Aj ≠ NULL
18 44 76 198
Post to the
X X Deletion of 262
80 92 141 272
7 12
X X X
X X
Ai ≠ NULL, Aj = NULL
Delete 12 18 44 76 198
X X
80 92 141 262
7 12
X X X
X X
Action : choose the smallest of the key element K” 272 286 350
from the subtree pointed to by Aj , delete K” and X X X X
replace K by K”
School of Computer Engineering
Deletion Case – 3 Result
83
Ai ≠ NULL, Aj = NULL
18 44 76 198
Post to the
X X Deletion of 12
80 92 141 262
7 10
X X X
X X
Ai ≠ NULL, Aj ≠ NULL
Delete 198 18 44 76 198
X X
80 92 141 262
7 12
X X X
X X
Ai ≠ NULL, Aj ≠ NULL
18 44 76 262
Post to the
X X Deletion of 198
C D F H I
A forest can be converted to a general tree (or simply tree i.e. number of subtrees
for any node is not required to be 0, 1, or 2) by adding a single node to serve as the
root node of the tree in which each of the original trees are sub-tree. Example –
B E G
C D F H I
School of Computer Engineering
Forest cont…
87
Conversely, deleting the root from a tree leaves behind a forest consisting of its
subtrees. (Obviously, this is how we got our forest from our original tree.)
B E G
C D F H I
Can we provide or say, nodes with 1000 pointer fields in order to be able to represent
general trees where nodes might have up to 1000 children? In any given case, most of
the fields of all the node records will be unused, so a great deal of memory is required -
and wasted. And what if we want to introduce a node with 1001 children? We have to
reconfigure the implementation to accommodate this one "anomalous" node. Surely,
this is not satisfactory. Remarkably, a forest can be represented by a binary tree. Note
that the resulting tree is a binary tree but not a binary search tree. Obviously, an
empty forest can be represented by the empty binary tree.
Exampl Step 1: Root Node of General tree becomes the Root node
e of binary tree.
Step 2: Now Root Node (A) has three child Nodes (B, H, E)
in general tree. The leftmost node (B) of the root node (A)
in the general tree becomes the left most node of the root
node (A) in binary tree.
Step 3: Now Node H becomes the right node of B and Node E becomes the right node of
H.
Step 4: Now Node B has only one left child node, which is C in general tree. So Node C
becomes left child of Node B in binary tree.
Step 5: Now Node E has two child nodes (F, G). The leftmost node (F) of the node (E) in
the general tree becomes the left most node of the node E in the binary tree.
M-way binary search trees have the advantage of having a node storing multiple values.
However it is essential that the height of the tree be kept as low as possible and
therefore their arises the need to maintain balanced m-way search trees. Such a balanced
m-way search tree is called B-tree.
❑ The root has at least two child nodes and at most m child nodes
❑ Internal nodes except the root have at least ⎡m/2⎤ child nodes and at most m child
nodes
❑ The number of keys in each internal node is one less than the number of child nodes
and these keys partition the keys in the subtrees of nodes in a manner similar to that
of m-way search trees
❑ All leaf nodes are on the same level
48
56 64 85
31 45
46 47
X X X 87 88 100 112
10 18 21
X X X X X
X X X X
58 62
X X X 49 51 52
36 40 42 X X X X
X X X X 67 75
X X X
Searching for a key in a B-tree is similar to the one on an m-way search key. The number
of accesses depends on the height h of the B-Tree.
Class Work
Draw the path to search for the key:
❑ 9
❑ 20
❑ 53
❑ 21
1. B-tree starts with a single root node (which is also a leaf node) at level 0.
2. Once the root node is full with m – 1 search key values and when attempt is made to
insert another entry in the tree, the root node splits into two nodes at level 1.
3. Only the middle value is kept in the root node, and the rest of the values are split
evenly between the other two nodes. i.e. the first (m-1)/2 values goes to left, the last
(m-1)/2 values goes to right.
4. When a non-root node is full and a new entry is inserted into it, that node is split into
two nodes at the same level, and the middle entry is moved to the parent node along
with two pointers to the new split nodes.
5. If the parent node is full, it is also split.
6. Splitting can propagate all the way to the root node, creating a new level if the root is
split.
B-Tree where m =5
Insert 17
Insert 6
Add it to the leftmost leaf. That overflows, so we split it: Left = [ 2 3 ], Middle = 5, Right = [ 6 7 ]
Left and Right become nodes; Middle is added to the node above with Left and Right as its children. The
node above (the root in this small example) does not overflow, so we are done.
Insert 21
Add it to the middle leaf. That overflows, so we split it: Left = [ 17 21 ], Middle = 22, Right = [ 44 45 ]
Left and Right become nodes; Middle is added to the node above with Left and Right as its children. The
node above (the root node in this small example) does not overflow, so we are done.
Insert 67
Add it to the rightmost tree. That overflows, so we split it: Left = [ 55 66 ], Middle = 67, Right = [ 68 70 ]
Left and Right become nodes; Middle is added to the node above with Left and Right as its children.
But now the node above does overflow. So it is split in exactly the same manner: so we split it:
Left = [ 5 10 ], Middle = 22, Right = [ 50 67 ]
Left and Right become nodes; , the children of Middle. If this were not the root, Middle would be added to
the node above and the process repeated. If there is no node above, as in this example, a new root is created
with Middle as its only value.
48
56 64 85
31 45
X X X X
X X X
Delete 85
48
56 64
31 45
X X X
X X X
31 45 31 42
46 47 46 47
Delete 45
X X X 10 18 21 X X X
10 18 21
X X X X
X X X X
36 40 42
36 40
X X X X
X X X
46
Delete 46
10 18 21 X X 45
10 18 21
X X X X X X
X X X X
36 40
Rich sibling for the 36 40 42
node with key 46 X X42 X
X X X X
46
Delete 46
10 18 21 X X
10 18 21 42 45
X X X X
X X X X X X42 X
In a B+ tree, the internal nodes have no data – only the leaves do!
❑ Each internal node still has up-to M-1 keys
❑ Subtree between two keys x and y contain leaves with values v such that x ≤ v < y
❑ Leaf nodes have up-to L (i.e. data items in leaf) sorted keys
❑ From the root to the leaf all paths should be of same length
Properties:
❑ Root (Special Case)
❑ Has between 2 and M children
❑ Internal Nodes
❑ Store up-to M-1 keys
❑ Have between ⎡M/2⎤ and M children
❑ Leaf Nodes Red arrow represents data elements
Green rectangle represents the node with key
❑ Where data is stored and data elements
❑ A binary tree has 9 nodes. The inorder and preorder traversal of T yields the
following sequence of node:
Inorder: E, A, C, K, F, H, D,B,G and Preorder: F, A, E, K, C, D, H, G, B
Draw the tree T
❑ Suppose T is a binary tree. Write a recursive & non-recursive algorithm to
find the number of leaf nodes, number of nodes and depth in T. Depth of T is
1 more than the maximum depths of the depths of the left and right subtrees
of T.
❑ Suppose T is a binary tree. Write a recursive & non-recursive algorithm to
find the height of T.
❑ Insert the following keys in the order to form the binary search tree
J, R, D, G, T, E, M, H, P, A, F, Q
❑ Insert the following keys in the order to form the binary search tree
50, 33, 44, 22, 77, 35, 60, 40
❑ Suppose a binary tree T is in memory. Write the pseudo code to delete all
terminals or leaf nodes in T
School of Computer Engineering
Assignments cont…
111
❑ Find out the inorder, preorder and postorder traversal of the following tree.
❑ Draw a complete binary tree with exactly six nodes. Put a different value in
each node. Then draw an array with six components and show where each of
the six node values would be placed in the array (using the usual array
representation of a complete binary tree).
❑ Draw a binary taxonomy tree that can be used for these four animals: Rabbit,
Horse, Whale, Snake. A binary taxonomy tree is also called as binary decision
tree that allows to going down the tree with simple test.
Ye No
s
Are you bigger than a cat Do you live underwater?
Ye No Ye No
s s
Kangaroo Mouse Trout Robin
❑ Write a function that traverses a threaded binary tree in postorder. What are
the time and space requirement of your method?
❑ Write a function that traverses a threaded binary tree in preorder. What are
the time and space requirement of your method?
❑ Write pseudo code to delete the node with key k from a binary search tree.
❑ Assume that a binary search tree is represented as a threaded binary search
tree. Write functions to search, insert and delete
❑ Write an algorithm to construct the binary tree with given preorder and
inorder.
❑ Write the pseudo code to construct the binary tree with given postorder and
inorder.
❑ Prove that every binary tree is uniquely by its preorder and inorder
sequences.
❑ Please provide constructive suggestions to this course in terms of lectures,
home works, or any other aspects
❑ http://www.geeksforgeeks.org/binary-tree-data-structure/
❑ http://www.geeksforgeeks.org/binary-search-tree-data-structure/
❑ https://www.tutorialspoint.com/data_structures_algorithms/tree_data_structure.htm
❑ http://btechsmartclass.com/DS/U3_T1.html
❑ http://btechsmartclass.com/DS/U3_T3.html
❑ https://www.hackerrank.com/domains/data-structures/trees
❑ https://www.youtube.com/watch?v=qH6yxkw0u78
❑ http://nptel.ac.in/courses/106102064/6
What is a B tree?
A B-tree of order m (the maximum number of children for each node) is a tree which
satisfies the following properties :
What is a B+ tree?
It is a dynamic, multilevel index, with maximum and minimum bounds on the number of
keys in each index segment. all records are stored at the lowest level of the tree; only keys
are stored in interior blocks.
Strictly for internal circulation (within KIIT) and reference only. Not for outside circulation without permission
Stack operations may involve initializing the stack, using it and then de-initializing it.
Apart from these basic stuffs, a stack is used for the following two primary operations −
push − pushing (storing) an element on the stack.
pop − removing (deleting) an element from the stack.
Parsing
Recursive Function
Function Call
Expression Evaluation Expression Representation
Expression Conversion Sr# Expression Meaning
Infix to Postfix 1 Infix Characterized by the placement of operators
Infix to Prefix between operands. E.g. plus sign in "2 + 2"
1 5 4
Position 1 2 3 4 5 6 7 8
TOP 3
TOP = 0 indicates that the stack is empty and TOP = N indicates that the stack is full
Since all the action happens at the top of the stack, a single linked list is a fine way to
represent the stack wherein the header/start always points to the top of the stack.
CC BB AA X
Represents Top
Pushing is inserting an element at the front of the list
Popping is removing an element from the front of the list
Push Before Push
CC BB AA X
After Push
DD CC BB AA X
School of Computer Engineering
Stack - Linked List Representation
11
DD CC BB AA X
After Pop
CC BB AA X
Stack Node Representation
struct node
{
int info;
struct node *next; N represents NULL
}*top;
void push()
{
int data; Top
scanf(“%d”, &data); Top
if (top == NULL)
{
top =(struct node *)malloc(*sizeof(struct node));
C
top->next = NULL; B
top->info = data; C B
} A X PUSH
else
{ X represents NULL A X
void pop()
{
struct node *tempTop = top;
Top
if (tempTop == NULL) Top
{
printf("\n Error "); C
return;
B
} B POP
else
tempTop = tempTop ->next; A X
A X
free(top);
top = tempTop;
Example
The above table shows the default behavior of operators. At any point of time in
expression evaluation, the order can be altered by using parenthesis.
For example − In a + b*c, the expression part b*c will be evaluated first, with
multiplication as precedence over addition. We here use parenthesis for a + b to be
evaluated first, like (a + b)*c.
Postfix:
Computer usually evaluates an arithmetic expression written in infix notation in
two steps:
1st Step - Converts the infix notation to Postfix notation
2nd Step - Evaluates the Postfix expression.
In each step, stack is the main tool used to accomplish the given task.
Prefix:
Has seen wide application in Lisp (programming language) s-expressions
Data Compression with Prefix Encoding
Standard scientific prefixes are used to denote powers of 10 e.g. kilo = 1e3
mega = 1e6 tera = 1e12 exa = 1e18
giga = 1e9 peta = 1e15
1. Start
2. Validate the Postfix expression for correctness
a) ‘(‘ and ‘)’ are in pairs
b) Operator is after the operands [Binary operators are considered only]
3. Add a right parenthesis ‘)” at the end of P. [This act as delimiter]
4. Scan P from left to right and repeat steps 5 and 6 for each element of P until the
delimiter “)” is encountered
5. If an operand is encountered, put it on STACK
6. If an operator is encountered, then
(a) Remove the two top elements of STACK, where A is the top element and B is the
next-to-top element
(b) Evaluate B A
(c ) Place the result of step (b) on STACK
7. Set value of the postfix expression equal to the top element of STACK
8. Stop
School of Computer Engineering
Example
22
P = 5, 6, 2, + , *, 12, 4, /, - [Postfix]
Note – Commas are used to separate the elements of P so that 5,6,2 is not interpreted as 562.
Q = 12 / (7-3) + 2 * (1+5) = 15
1. Start
2. Validate the Prefix Expression for correctness
a) ‘(‘ and ‘)’ are in pairs
b) Operator is before the operands [Binary operators are considered only]
3. Scan P from right to left and repeat steps 5 and 6 for each element of P until it ends.
4. If an operand is encountered, put it on STACK
5. If an operator is encountered, then
(a) Remove the two top elements of STACK, where A is the top element and B is the
next-to-top element
(b) Evaluate A B
(c ) Place the result of step (b) on STACK
6. Set value of the prefix expression equal to the top element of STACK
7. Stop
P = -, *, +, 4, 3, 2, 5 [Prefix]
Note – Commas are used to separate the elements of P
- * + 4 3 2 5
(7) (6) (5) (4) (3) (2) (1)
Q:A+(B*C–(D/E îF)*G)*H
So first, we push “(“ onto stack, and then add “)” to the end of the Q to obtain:
A + ( B * C - ( D / E î F ) * G ) * H )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
A + ( B * C - ( D / E î F ) * G ) * H )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Consider the infix expression Q: ((A + B) * D) î (E-F). Translate Q into its equivalent
postfix expression P
Symbol Scanned STACK Expression P
1 ( ((
2 ( (((
3 A ((( A
4 + (((+ A
5 B (((+ AB
6 ) (( AB +
7 * ((* AB +
8 D ((* AB +D
9 ) ( AB +D*
10 î (î AB +D*
11 ( (î( AB+D*
12 E (î( AB+D*E
13 - (î(- AB+D*E F
14 F (î(- AB+D*E F
15 ) (î AB+D*E F–
16 AB+D*E F–î
Q : (A+B î C)*D+E î F
Step 1 – Infix expression is correct
Step 2 –
a) Reversing the expression produce F î E + D * ) C î B + A (
b) Reverse the bracket, so making every '(' as ')' and every ')' as '(‘
revised expression is F î E + D * ( C î B + A )
Step 3 – Postfix expression of step 2 produce F E î D C B î A + * +
Step 4 – Reversing the expression produced in step 3 becomes
+ *+AîBCDî E5
Result: + * + A î B C D î E 5
Operating System
queue of print jobs to send to the printer
queue of programs / processes to be run
queue of network data packets to send
Programming
modeling a line of customers or clients
storing a queue of computations to be performed in order
Real World
people on an escalator or waiting in a line
cars at a gas station (or on an assembly line)
4 8 6
Position 1 2 3 4 5 6 7 8
Keeps track of the number of items in the queue and the position of the front element
(at the front of the queue), the rear element (at the rear). The position of the front
element is stored in the front member variable. The next item is after the first one and
so on until the rear of the queue that occurs at the index stored in a member variable
called rear.
FRONT = 0 and REAR = 0 indicates that the queue is empty and REAR = N indicates that the
queue is full
School of Computer Engineering
Enqueue Operation
37
1 2 3 4 5 6 ... FRONT
0
0 REAR
1 2 3 4 5 6 ...
1 FRONT
4 8 6
3 REAR
Let’s an element leaves the queue
1 2 3 4 5 6 ...
2 FRONT
4 8 6
3 REAR
Node Representation
struct node
{
char info[50];
struct node *next;
}*front, *rear;
School of Computer Engineering
Enqueue Operation
42
Post Insertion
Post Deletion
BEGIN
IF (FRONT = NULL) THEN
DISPLAY “Queue Underflow"
EXIT
END IF
struct * node temp = FRONT
ITEM = temp->info
FRONT = FRONT->next
FREE(temp)
RETURN ITEM
END
School of Computer Engineering
Class Work
46
Once the linear queue is full, even though few elements from the front are deleted & some
occupied space is relieved, it is not possible to add anymore new elements, as the rear has
already reached the queue’s rear most position.
Delete 3 elements
This situation also says that queue is full and we can not insert the new
element because, 'rear' is still at last position. In above situation, even
though we have empty positions in the queue we can not make use of them
to insert new element. This is the major problem in normal queue data
structure. To overcome this problem we use circular queue data structure.
Circular Queue is a linear data structure in which the operations are performed based on
FIFO (First In First Out) principle and the last position is connected back to the first
position to make a circle and the graphical representation of a circular queue is as
follows...
Rear
Rear
Rear
Rear
1. Start 1. Start
2. IF (FRONT = REAR) [QUEUE is Full] 2. IF (REAR = FRONT) [QUEUE is Full]
Display “Over flow” Display “Over flow”
EXIT EXIT
END IF END IF
3. FRONT = FRONT + 1 3. QUEUE[REAR] = ITEM
4. QUEUE[FRONT] = ITEM 4. REAR = REAR - 1
5. Stop 5. Stop
1. Start 1. Start
2. IF (FRONT = 0) [QUEUE is Empty] 2. IF (REAR = N) [QUEUE is Empty]
DISPLAY “Under flow” DISPLAY“Under flow”
EXIT EXIT
END IF END IF
3. ITEM = QUEUE[FRONT] 4. ITEM = QUEUE[REAR]
4. FRONT = FRONT - 1 5. REAR = REAR + 1
5. RETURN ITEM 6. RETURN ITEM
6. Stop 7. Stop
A priority queue is a collection of elements such that each element has been
assigned a priority and such that the order in which elements are deleted and
processed comes from the following rules –
Each node in the list will contain three items of information: an information
field INFO, a priority number PRN and a link number LINK.
Systematic diagram
Head
A1 B2 C2 D3
Deletion
1. Start
2. Find the smallest K such that FRONT[K] <> NULL
3. Delete and Process the front element in row K of Queue
4. Stop
Insertion
1. Start
2. Insert ITEM as the rear element in row M of queue
3. Stop
Assignment 1 Assignment 2
Write an algorithm to convert an infix Write pseudo code to check whether a given
expression into it equivalent postfix expression. postfix expression is correctly parenthesized
Explain the execution of algorithm using the
following expression. Assignment 3
Assignment 4 Assignment 5
Write C functions for insertion, deletion, Write an algorithm to copy the data elements of
traversal operation for circular queues one stack to other without changing the order
and without using any other data structure
Assignment 6 Assignment 7
Write C functions for insertion, deletion, Write C functions for insertion, deletion,
traversal operation for input restricted deques traversal operation for priority queues
Assignment 8 Assignment 9
Write an algorithm to check for balanced Write pseudo code for recursive function to
parentheses (, ), {, }, [ and ] in an expression display the string in reverse order.
Assignment 10 Assignment 11
Write an algorithm to convert postfix expression Write an algorithm to convert prefix expression
to infix expression. to infix expression.
Assignment 12 Assignment 13
Write an algorithm to convert postfix expression Write an algorithm to convert prefix expression
to prefix expression. to postfix expression.
Assignment 14
1. You are given 2 queues where each queue contains timestamp pair price. You have to
print < price 1 price 2 > for all those timestamps where abs(ts1 – ts2) <= 1 second
where ts1 and price 1 from 1st queue and ts2 and price 2 from 2nd queue.
2. Given an array, print the Next Greater Element (NGE) for every element. The Next
greater Element for an element x is the first greater element on the right side of x in
array. Elements for which no greater element exist, consider next greater element as
-1. Examples:
a) For any array, rightmost element always has next greater element as -1.
b) For an array which is sorted in decreasing order, all elements have next greater
element as -1.
c) For the input array [4, 5, 2, 25}, the next greater elements for each element are as
follows.
Element NGE
4 5
5 25
2 25
25 -1
7. Suppose there is a circle. There are n petrol pumps on that circle. You are given two
sets of data.
Calculate the first point from where a truck will be able to complete the circle (The
truck will stop at each petrol pump and it has infinite capacity). Expected time
complexity is O(n). Assume for 1 litre petrol, the truck can go 1 unit of distance.
For example, let there be 4 petrol pumps with amount of petrol and distance to next
petrol pump value pairs as {4, 6}, {6, 5}, {7, 3} and {4, 5}. The first point from where
truck can make a circular tour is 2nd petrol pump. Output should be “start = 1”
(index of 2nd petrol pump).
8. Given an array of non-negative integers. Find the largest multiple of 3 that can be
formed from array elements. For example, if the input array is {8, 1, 9}, the output
should be “9 8 1”, and if the input array is {8, 1, 7, 6, 0}, output should be “8 7 6 0”.
9. Given an array and an integer k, find the maximum for each and every contiguous
subarray of size k.
Examples:
Input :
arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, k = 3
Output :
3345556
Input :
arr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, k = 4
Output :
10 10 10 15 15 90 90
10. We are given queue data structure, the task is to implement stack using only given
queue data structure.
11. Given a matrix of dimension m*n where each cell in the matrix can have values 0, 1
or 2 which has the following meaning:
0: Empty cell, 1: Cells have fresh oranges, 2: Cells have rotten oranges .
So we have to determine what is the minimum time required so that all the oranges
become rotten. A rotten orange at index [i,j] can rot other fresh orange at indexes [i-
1,j], [i+1,j], [i,j-1], [i,j+1] (up, down, left and right). If it is impossible to rot every
orange then simply return -1.
Examples:
Input: arr[][C] = { {2, 1, 0, 2, 1},
{1, 0, 1, 2, 1},
{1, 0, 0, 2, 1}};
Output:
All oranges can become rotten in 2 time frames.
School of Computer Engineering
Supplementary Reading
71
http://www.geeksforgeeks.org/stack-data-structure/
http://www.geeksforgeeks.org/queue-data-structure/
https://www.tutorialspoint.com/data_structures_algorithms/stack_algorithm.htm
https://www.tutorialspoint.com/data_structures_algorithms/dsa_queue.htm
http://www.geeksforgeeks.org/implement-stack-using-queue/
http://www.geeksforgeeks.org/queue-using-stacks/
http://nptel.ac.in/courses/106102064/2
http://nptel.ac.in/courses/106102064/3
http://freevideolectures.com/Course/2279/Data-Structures-And-Algorithms/2
http://freevideolectures.com/Course/2279/Data-Structures-And-Algorithms/3
What is Stack?
Stacks are data structures that allow us to insert and remove items. The operate
like a stack of papers or books on our desk - we add new things to the top of the
stack to make the stack bigger, and remove items from the top as well to make
the stack smaller. This makes stacks a LIFO (Last In First Out) data structure –
the data we have put in last is what we will get out first.
What is Queue?
A queue is a data structure where we add elements at the back and remove
elements from the front. In that way a queue is like “waiting in line”: the first
one to be added to the queue will be the first one to be removed from the queue.
This is also called a FIFO (First In First Out) data structure.
Implement Stack using Queue: We are given a stack data structure with push
and pop operations, the task is to implement a queue using instances of stack
data structure and operations on them.
Solution: http://www.geeksforgeeks.org/queue-using-stacks/
Implement Queue using Stack: We are given a queue data structure with
enqueue and deque operations, the task is to implement a stack using instances
of queue data structure and operations on them.
Solution: http://www.geeksforgeeks.org/implement-stack-using-queue/