Prefix and Postfix Expressions in Data Structure

Data StructureAnalysis of AlgorithmsAlgorithms

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

  • Prefix

  • Postfix

Infix notations are normal notations, that are used by us while write different mathematical expressions. The Prefix and Postfix notations are quite different.

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.

Example

Expression NoInfix NotationPrefix NotationPostfix Notation
1a + b+ a ba b +
2(a + b) * c* + a b ca b + c *
3a * (b + c)* a + b ca b c + *
4a / b + c / d+ / a b / c da b / c d / +
5(a + b) * (c + d)* + a b + c da b + c d + *
6((a + b) * c) - d- * + a b c da b + c * d -

Parsing Expression

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.

raja
Published on 11-Aug-2020 06:37:53
Advertisements