0% found this document useful (0 votes)
20 views29 pages

DS UNIT-3

Uploaded by

idan06788
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views29 pages

DS UNIT-3

Uploaded by

idan06788
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

D. L.

PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR


Subject : Data Structure (629401) MCA SEM - II

UNIT-3
Nonlinear Data Structures:

Tree – Basic Tree Concepts

We read the linear data structures like an array, linked list, stack and queue in which all the elements are
arranged in a sequential manner. The different data structures are used for different kinds of data.

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 defined as a collection of objects or entities known as nodes that are
linked together to represent or simulate hierarchy.
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. In the above tree structure, the node contains the name of the
employee, so the type of data would be a string.
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.

Let's consider the tree structure, which is shown below:

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

Basic Terminologies In Tree Data Structure:


 Parent Node: The node which is a predecessor of a node is called the parent node of that
node. {B} is the parent node of {D, E}.
 Child Node: The node which is the immediate successor of a node is called the child node of
that node. Examples: {D, E} are the child nodes of {B}.
 Root Node: The topmost node of a tree or the node which does not have any parent node is
called the root node. {A} is the root node of the tree. A non-empty tree must contain exactly one
root node and exactly one path from the root to all other nodes of the tree.
 Leaf Node or External Node: The nodes which do not have any child nodes are called leaf
nodes. {K, L, M, N, O, P, G} are the leaf nodes of the tree.
 Ancestor of a Node: Any predecessor nodes on the path of the root to that node are called
Ancestors of that node. {A,B} are the ancestor nodes of the node {E}
 Descendant: A node x is a descendant of another node y if and only if y is an ancestor of y.
 Sibling: Children of the same parent node are called siblings. {D,E} are called siblings.
 Level of a node: The count of edges on the path from the root node to that node. The root
node has level 0.
 Internal node: A node with at least one child is called Internal Node.
 Neighbour of a Node: Parent or child nodes of that node are called neighbors of that node.
 Subtree: Any node of the tree along with its descendant.

Properties of Tree data structure

o Recursive data structure: The tree is also known as a recursive data structure. A tree can be
defined as recursively because the distinguished node in a tree data structure is known as a root
node. The root node of the tree contains a link to all the roots of its subtrees. The left subtree is
shown in the yellow color in the below figure, and the right subtree is shown in the red color. The
left subtree can be further split into subtrees shown in three different colors. Recursion means
reducing something in a self-similar manner. So, this recursive property of the tree data structure
is implemented in various applications.

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

o Number of edges: If there are n nodes, then there would n-1 edges. Each arrow in the structure
represents the link or path. Each node, except the root node, will have atleast one incoming link
known as an edge. There would be one link for the parent-child relationship.
o Depth of node x: The depth of node x can be defined as the length of the path from the root to
the node x. One edge contributes one-unit length in the path. So, the depth of node x can also be
defined as the number of edges between the root node and the node x. The root node has 0
depth.
o Height of node x: The height of node x can be defined as the longest path from the node x to
the leaf node.

Based on the properties of the Tree data structure, trees are classified into various categories.

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.

In programming, the structure of a node can be defined as:

struct node
{
int data;
struct node *left;
struct node *right;
}

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

Application of Tree In DSA


As mentioned above, trees are one of the essential data structures. They have several applications which
help us to achieve simple and complex tasks.
1. File systems: Trees are used to organize and store files in a hierarchical structure.

2. Decision-making: Trees are used to model decision-making processes, where each node
represents a decision point, and each branch represents a possible outcome.

3. Expression parsing: Trees are used to represent mathematical expressions and can be used to
evaluate them.

4. Huffman coding: Trees are used to compress data by representing frequently occurring data with
shorter codes and less frequent data with longer codes.

5. Graph algorithms: Many graph algorithms, such as depth-first search and breadth-first search, are
implemented using tree data structures.

6. Artificial Intelligence: Decision Trees and Random Forest are used in machine learning and AI as
models.

7. Database indexing: Trees are used to index and organize data in databases for faster retrieval.

8. Network routing protocols: Trees are used to organize and optimize communication networks.

9. Compiler Design: Syntax trees are used in compilers to represent the syntactic structure of a
program.

10. Game AI: Game AI often uses tree data structures to model game states and possible moves in a
game and to evaluate them using game-specific metrics.

Types of Tree data structure

The following are the types of a tree data structure:

o 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.

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

There can be n number of subtrees in a general tree. In the general tree, the subtrees are
unordered as the nodes in the subtree cannot be ordered.

Every non-empty tree has a downward edge, and these edges are connected to the nodes known
as child nodes. The root node is labeled with level 0. The nodes that have the same parent are
known as siblings.

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.

o Binary Search tree: Binary search tree is a non-linear data structure in which one node is
connected to n number of nodes. It is a node-based data structure. A node can be represented in
a binary search tree with three fields, i.e., data part, left-child, and right-child. A node can be
connected to the utmost two child nodes in a binary search tree, so the node contains two
pointers (left child and right child pointer). Every node in the left subtree must contain a value less
than the value of the root node, and the value of each node in the right subtree must be bigger
than the value of the root node.

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

AVL tree

It is one of the types of the binary tree, or we can say that it is a variant of the binary search tree. AVL tree
satisfies the property of the binary tree as well as of the binary search tree. It is a self-balancing binary
search tree that was invented by Adelson Velsky Lindas. Here, self-balancing means that balancing the
heights of left subtree and right subtree. This balancing is measured in terms of the balancing factor.

We can consider a tree as an AVL tree if the tree obeys the binary search tree as well as a balancing factor.
The balancing factor can be defined as the difference between the height of the left subtree and the
height of the right subtree. The balancing factor's value must be either 0, -1, or 1; therefore, each node
in the AVL tree should have the value of the balancing factor either as 0, -1, or 1.

Red-Black Tree

The red-Black tree is the binary search tree. The prerequisite of the Red-Black tree is that we should
know about the binary search tree. In a binary search tree, the value of the left-subtree should be less
than the value of that node, and the value of the right-subtree should be greater than the value of that
node. As we know that the time complexity of binary search in the average case is log 2n, the best case is
O(1), and the worst case is O(n).

When any operation is performed on the tree, we want our tree to be balanced so that all the operations
like searching, insertion, deletion, etc., take less time, and all these operations will have the time
complexity of log2n.

The red-black tree is a self-balancing binary search tree. AVL tree is also a height balancing binary search
tree then why do we require a Red-Black tree. In the AVL tree, we do not know how many rotations
would be required to balance the tree, but in the Red-black tree, a maximum of 2 rotations are required
to balance the tree. It contains one extra bit that represents either the red or black color of a node to
ensure the balancing of the tree.

Basic Operation Of Tree Data Structure:


 Create – create a tree in the data structure.
 Insert − Inserts data in a tree.
 Search − Searches specific data in a tree to check whether it is present or not.
 Traversal:
 Preorder Traversal – perform Traveling a tree in a pre-order manner in the data
structure.
 In order Traversal – perform Traveling a tree in an in-order manner.
 Post-order Traversal –perform Traveling a tree in a post-order manner.

Tree traversal (Inorder, Preorder an Postorder)


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

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

o Inorder traversal
o Postorder traversal

So, in this article, we will discuss the above-listed techniques of traversing a tree. Now, let's start
discussing the ways of tree traversal.

Preorder traversal

This technique follows the 'root left right' policy. It means that, first root node is visited after that the left
subtree is traversed recursively, and finally, right subtree is recursively traversed. As the root node is
traversed before (or pre) the left and right subtree, it is called preorder traversal.

So, in a preorder traversal, each node is visited before both of its subtrees.

he applications of preorder traversal include -

o It is used to create a copy of the tree.


o It can also be used to get the prefix expression of an expression tree.

Algorithm

Until all nodes of the tree are not visited

o Step 1 - Visit the root node


o Step 2 - Traverse the left subtree recursively.
o Step 3 - Traverse the right subtree recursively.

Procedure : RPREORDER(T)

 Given a binary tree whose root node address is given by pointer variable T and whose
node structure issame as described below. This procedure traverses the tree in
preorder, in a recursive manner.

LPTR DATA RPTR

1. [Check for empty Tree]


If T = NULL
then write (‘Empty Tree’)
return

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

else write (DATA(T))

2. [Process the Left Subtree]


If LPTR (T) ≠ NULL
then RPREORDER (LPTR (T))

3. [Process the Right Subtree]


If RPTR (T) ≠ NULL
then RPREORDER (RPTR (T))

4. [Finished]
return

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 -

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

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

Example of preorder traversal

Now, let's see an example of preorder traversal. It will be easier to understand the process of preorder
traversal using an example.

The nodes with yellow color are not visited yet. Now, we will traverse the nodes of the above tree using
preorder traversal.

After the completion of preorder traversal, the final output is -

40, 30, 25, 15, 28, 35, 50, 45, 60, 55, 70

Postorder traversal

This technique follows the 'left-right root' policy. It means that the first left subtree of the root node is
traversed, after that recursively traverses the right subtree, and finally, the root node is traversed. As the
root node is traversed after (or post) the left and right subtree, it is called postorder traversal.

So, in a postorder traversal, each node is visited after both of its subtrees.

The applications of postorder traversal include -

o It is used to delete the tree.


o It can also be used to get the postfix expression of an expression tree.

Algorithm

Until all nodes of the tree are not visited

Step 1 - Traverse the left subtree recursively.


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

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

Procedure : RPOSTORDER(T)

 Given a binary tree whose root node address is given by pointer variable T and whose
node structure issame as described below. This procedure traverses the tree in
postorder, in a recursive manner.

1. [Check for empty Tree]


If T = NULL
then write (‘Empty Tree’)
return

2. [Process the Left Subtree]


If LPTR (T) ≠ NULL
then RPOSTORDER (LPTR (T))

3. [Process the Right Subtree]


If RPTR (T) ≠ NULL
then RPOSTORDER (RPTR (T))

4. [Process the root node]


write (DATA(T))

5. [Finished]
return

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.

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

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.

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

This technique follows the 'left root right' policy. It means that first left subtree is visited after that root
node is traversed, and finally, the right subtree is traversed. As the root node is traversed between the left
and right subtree, it is named inorder traversal.

So, in the inorder traversal, each node is visited in between of its subtrees.

The applications of Inorder traversal includes -

o It is used to get the BST nodes in increasing order.


o It can also be used to get the prefix expression of an expression tree.

Algorithm

Until all nodes of the tree are not visited

Step 1 - Traverse the left subtree recursively.


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

Procedure : RINORDER(T)

 Given a binary tree whose root node address is given by pointer variable T and whose
node structure issame as described below. This procedure traverses the tree in inorder,
in a recursive manner.
1. [Check for empty Tree]
If T = NULL

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

then write (‘Empty Tree’)


return

2. [Process the Left Subtree]


If LPTR (T) ≠ NULL
then RINORDER (LPTR (T))

3. [Process the root node]


write (DATA(T))

4. [Process
the Right
Subtree] If
RPTR (T) ≠
NULL then
RINORDER
(RPTR (T))

5. [Finished]
return

Example

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

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

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

Storage Representation of Binary Tree :-

binary tree data structure is represented using two methods. Those methods are as follows...

1. Array Representation
2. Linked List Representation

Consider the following binary tree...

1. Array Representation of Binary Tree


In array representation of a binary tree, we use one-dimensional array (1-D Array) to represent a binary tree.
Consider the above example of a binary tree and it is represented as follows...

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

To represent a binary tree of depth 'n' using array representation, we need one dimensional array with a maximum
size of 2n + 1.

2. Linked List Representation of Binary Tree


We use a double linked list to represent a binary tree. In a double linked list, every node consists of three fields. First
field for storing left child address, second for storing actual data and third for storing right child address.
In this linked list representation, a
node has the following structure...

The above example of the binary tree represented using Linked list representation is shown as follows...

Convert a Generic Tree(N-array Tree) to Binary Tree



Prerequisite: Generic Trees(N-array Trees)
In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to
convert a Generic(N-array Tree) to a Binary Tree:
 The root of the Binary Tree is the Root of the Generic Tree.
 The left child of a node in the Generic Tree is the Left child of that node in the Binary Tree.
 The right sibling of any node in the Generic Tree is the Right child of that node in the Binary Tree.
Examples:
Convert the following Generic Tree to Binary Tree:

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

Below is the Binary Tree of the above Generic Tree:

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

Note: If the parent node has only the right child in the general tree then it becomes the rightmost
child node of the last node following the parent node in the binary tree. In the above example, if
node B has the right child node L then in binary tree representation L would be the right child of
node D.

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II
Below are the steps for the conversion of Generic Tree to Binary Tree:
1. As per the rules mentioned above, the root node of general tree A is the root node of the binary
tree.
2. Now the leftmost child node of the root node in the general tree is B and it is the leftmost child
node of the binary tree.
3. Now as B has E as its leftmost child node, so it is its leftmost child node in the binary tree
whereas it has C as its rightmost sibling node so it is its right child node in the binary tree.
4. Now C has F as its leftmost child node and D as its rightmost sibling node, so they are its left
and right child node in the binary tree respectively.
5. Now D has I as its leftmost child node which is its left child node in the binary tree but doesn’t
have any rightmost sibling node, so doesn’t have any right child in the binary tree.
6. Now for I, J is its rightmost sibling node and so it is its right child node in the binary tree.
7. Similarly, for J, K is its leftmost child node and thus it is its left child node in the binary tree.
8. Now for C, F is its leftmost child node, which has G as its rightmost sibling node, which
has H as its just right sibling node and thus they form their left, right, and right child node
respectively.

Algorithm
We will understand the algorithm stepwise. Let's go.
 Create a generic tree and call the "genericToBinary" function.

o Check if the root node is null. If yes, return null.

o Check if the root node has no children. If true, return the root as the node is already a leaf node.

o Check if the root node has only one child. If yes, call the "genericToBinary" function recursively
with the child node and set it as the left child of the current node in the binary tree.

o If the root has multiple children, set the left child of the binary tree as the result of recursively
calling the genericToBinary function with the first child node as the argument.

o Set the right child of the binary tree as the result of recursively calling the genericToBinary
function with the next sibling node as the argument.

o Iterate over the remaining child nodes and set them as the left child of the rightmost node in the
binary tree.

o Return the root of the binary tree.

Print the binary tree using the preorder traversal.

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II
The Manipulation of Arithmetic Expression :

An expression is any word or group of words or symbols that generates a value on


evaluation. Parsing expression means analyzing the expression for its words or symbols
depending on a particular criterion. Expression parsing is a term used in a programming
language to evaluate arithmetic and logical expressions.

The way to write arithmetic expression is known as a notation. An arithmetic expression can
be written in three different but equivalent notations, i.e., without changing the essence or
output of an expression. These notations are −

 Infix Notation
 Prefix (Polish) Notation
 Postfix (Reverse-Polish) Notation

These notations are named as how they use operator in expression. We shall learn the same
here in this chapter.

Infix Notation

We write expression in infix notation, e.g. a - b + c, where operators are used in-between
operands. It is easy for us humans to read, write, and speak in infix notation but the same
does not go well with computing devices. An algorithm to process infix notation could be
difficult and costly in terms of time and space consumption.

Prefix Notation

In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands.
For example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known
as Polish Notation.

Postfix Notation

This notation style is known as Reversed Polish Notation. In this notation style, the operator
is postfixed to the operands i.e., the operator is written after the operands.

For example, ab+. This is equivalent to its infix notation a + b.

The following table briefly tries to show the difference in all three notations –

Sr.No. Infix Notation Prefix Notation Postfix Notation

1 a+b +ab ab+

2 (a + b) ∗ c ∗+abc ab+c∗

3 a ∗ (b + c) ∗a+bc abc+∗

4 a/b+c/d +/ab/cd ab/cd/+

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

5 (a + b) ∗ (c + d) ∗+ab+cd ab+cd+∗

6 ((a + b) ∗ c) - d -∗+abcd ab+c∗d-

Parsing Expressions

As we have discussed, it is not a very efficient way to design an algorithm or program to


parse infix notations. Instead, these infix notations are first converted into either postfix or
prefix notations and then computed.

To parse any arithmetic expression, we need to take care of operator precedence and
associativity also.

Precedence

When an operand is in between two different operators, which operator will take the
operand first, is decided by the precedence of an operator over others. For example −

As multiplication operation has precedence over addition, b * c will be evaluated first. A


table of operator precedence is provided later.

Associativity

Associativity describes the rule where operators with the same precedence appear in an
expression. For example, in expression a + b − c, both + and − have the same precedence,
then which part of the expression will be evaluated first, is determined by associativity of
those operators. Here, both + and − are left associative, so the expression will be evaluated
as (a + b) − c.

Precedence and associativity determines the order of evaluation of an expression. Following


is an operator precedence and associativity table (highest to lowest) −

Sr.No. Operator Precedence Associativity

Right
1 Exponentiation ^ Highest
Associative

Multiplication ( ∗ ) & Second Left


2
Division ( / ) Highest Associative

Addition ( + ) & Left


3 Lowest
Subtraction ( − ) Associative

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 −

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

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.

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.
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

+ + 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

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

) + 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+

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+.

Conversion of Infix to Prefix using Stack

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

If we are converting the expression from infix to prefix, we need first to reverse the expression.

The Reverse expression would be:

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

To obtain the prefix expression, we have created a table that consists of three columns, i.e., input expression, stack, and
prefix expression. When we encounter any symbol, we simply add it into the prefix expression. If we encounter the operator,
we will push it into the stack.

Input expression Stack Prefix expression

Q Q

+ + Q

T + QT

* +* QT

V +* QTV

/ +*/ QTV

U +*/ QTVU

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

/ +*// QTVU

W +*// QTVUW

* +*//* QTVUW

) +*//*) QTVUW

P +*//*) QTVUWP

^ +*//*)^ QTVUWP

O +*//*)^ QTVUWPO

( +*//* QTVUWPO^

+ ++ QTVUWPO^*//*

N ++ QTVUWPO^*//*N

* ++* QTVUWPO^*//*N

M ++* QTVUWPO^*//*NM

- ++- QTVUWPO^*//*NM*

L ++- QTVUWPO^*//*NM*L

+ ++-+ QTVUWPO^*//*NM*L

K ++-+ QTVUWPO^*//*NM*LK

QTVUWPO^*//*NM*LK+-++

The above expression, i.e., QTVUWPO^*//*NM*LK+-++, is not a final expression. We need to reverse this expression to
obtain the prefix expression.

Rules for the conversion of infix to prefix expression:

o First, reverse the infix expression given in the problem.


o Scan the expression from left to right.
o Whenever the operands arrive, print them.
o If the operator arrives and the stack is found to be empty, then simply push the operator into the stack.
o If the incoming operator has higher precedence than the TOP of the stack, push the incoming operator into the
stack.
o If the incoming operator has the same precedence with a TOP of the stack, push the incoming operator into the
stack.
o If the incoming operator has lower precedence than the TOP of the stack, pop, and print the top of the stack. Test
the incoming operator against the top of the stack again and pop the operator from the stack till it finds the
operator of a lower precedence or same precedence.
o If the incoming operator has the same precedence with the top of the stack and the incoming operator is ^, then
pop the top of the stack till the condition is true. If the condition is not true, push the ^ operator.
o When we reach the end of the expression, pop, and print all the operators from the top of the stack.
o If the operator is ')', then push it into the stack.

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

o If the operator is '(', then pop all the operators from the stack till it finds ) opening bracket in the stack.
o If the top of the stack is ')', push the operator on the stack.
o At the end, reverse the output.

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.

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 to Action Stack Description


be scanned

L Push L into the stack L

K Push K into the stack L, K

A Push A into the stack L, K, A

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

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

C Push C into the stack AK/L-, C

B Push B into the stack AK/L-,


C, B

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

A Push A into the stack AK/L-,

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

BC/, A

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

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

Conversion of Postfix to Prefix expression

There are two ways of converting a postfix into a prefix expression:

1. Conversion of Postfix to Prefix expression manually.


2. Conversion of Postfix to Prefix expression using stack.

Conversion of Postfix to Prefix expression manually

The following are the steps required to convert postfix into prefix expression:

o Scan the postfix expression from left to right.


o Select the first two operands from the expression followed by one operator.
o Convert it into the prefix format.
o Substitute the prefix sub expression by one temporary variable
o Repeat this process until the entire postfix expression is converted into prefix expression.

Let's understand through an example.

ab-c+

First, we scan the expression from left to right. We will move '-' operator before the operand ab.

-abc+

The next operator '+' is moved before the operand -abc is shown as below:

+-abc

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.

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II
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 the AB


stack

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

C Push C into the +ABC


stack

D Push D into +ABCD


the stack

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

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

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

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

Introduction to Multi Linked List


A multi-linked list is a special type of list that contains two or more logical key sequences. Before checking
details about multi-linked list, see what is a linked list. A linked list is a data structure that is free from any size
restriction until the heap memory is not full. We have seen different types of linked lists, such as Singly Linked
List, Circular Linked List, and Doubly Linked List. Here we will see about multi-linked list.
In a multi-linked list, each node can have N number of pointers to other nodes. A multi -linked list is generally used
to organize multiple orders of one set of elements.
Properties of Multi-Linked List:
The properties of a multi-linked list are mentioned below.
 It is an integrated list of related structures.
 All the nodes are integrated using links of pointers.
 Linked nodes are connected with related data.
 Nodes contain pointers from one structure to the other.
Structure of Multi-linked list:
The structure of a multi-linked list depends on the structure of a node. A single node generally contains two things:
 A list of pointers
 All the relevant data.
Shown below is the structure of a node that contains only one data and a list of pointers.
typedef struct node {
int data;
vector<struct node*> pointers;
} Node;

Use cases of Multi-Linked Lists:


Some use cases of a multi-linked list are:
 Multiple orders of one set of elements
 Representation of a sparse matrix
 List of List
Multiple orders of one set of elements:
 A multi-linked list is a more general linked list with multiple links from nodes.
 For example, suppose the task is to maintain a list in multiple orders, age and name here, we can define a
Node that has two references, an age pointer and a name pointer.
 Then it is possible to maintain one list, where if we follow the name pointer we can traverse the list in
alphabetical order
 And if we try to traverse the age pointer, we can traverse the list by age also.
 This type of node organization may be useful for maintaining a customer list in a bank where the same list can
be traversed in any order (name, age, or any other criteria) based on the need. For example, suppose my
elements include the name of a person and his/her age. e.g.
(ANIMESH, 19), (SUMIT, 17), (HARDIK, 22), (ISHA, 18)

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II
Inserting into this structure is very much like inserting the same node into two separate lists. In multi-linked lists it
is quite common to have back-pointers, i.e. inverses of each of the forward links; in the above example, this would
mean that each node had 4pointers.

Representation of Sparse Matrix:


Multi Linked Lists are used to store sparse matrices. A sparse matrix is such a matrix that has few non-zero
values. If we use a normal array to store such a matrix, it will end up wasting lots of space.

The sparse matrix can be represented by using a linked list for every row and column.
A node in a multi-linked list has four parts:
 The first part stores the data.
 The second stores the pointer to the next row.
 Third for the pointer to the next column and
 Fourth for storing the coordinate number of the cell in the matrix.

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

List of List:
A multi-linked list can be used to represent a list of lists. For example, we can create a linked list where each node
is itself a list and have pointers to other nodes.
See the structure below:
 It is a 2-dimensional data structure.
 Here each node has three fields:
 The first field stores the data.
 The second field stores a pointer to the child node.
 The third field stores the pointer to the next node.

By : Cheerag Jayswal
D. L. PATEL INSTITUTE OF MANAGEMENT & TECHNOLOGY MCA COLLEGE, HIMMATNAGAR
Subject : Data Structure (629401) MCA SEM - II

Advantages of Multi-Linked List:


The advantages of a multi-linked list are:
 Sets of same data can be processed into multiple sequences.
 Data are not duplicated anywhere.
 Data of one kind exist only once in the list.

By : Cheerag Jayswal

You might also like