Skip to content

Algorithm: Infix, Prefix and Postfix Traversal

1. Notations Overview

NotationFormat ExampleOperator Position
InfixA + BBetween operands
Prefix+ A BBefore operands
PostfixA B +After operands

2. Why Use Postfix/Prefix?

  • Removes need for parentheses βœ…
  • Unambiguous evaluation βœ…
  • Ideal for computers & compilers
  • Easily evaluated using Stacks

3. Operator Precedence

OperatorPrecedenceAssociativity
^3Right to Left
* / %2Left to Right
+ -1Left to Right

4. Infix to Postfix Conversion (Using Stack)

Steps:

  1. If operand β†’ add to output
  2. If ( β†’ push to stack
  3. If ) β†’ pop till (
  4. If operator:
    • Pop operators from stack β‰₯ precedence
    • Then push current operator

Example: A + B * C

Postfix: A B C * +

Example: (A + B) * C

Postfix: A B + C *

5. Infix to Prefix Conversion

Steps:

  1. Reverse infix string
  2. Replace ( with ), and vice versa
  3. Convert to postfix
  4. Reverse result β†’ it’s prefix

Example: A + B * C

1. Reverse: C * B + A
2. Postfix: C B * A +
3. Reverse: + A * B C
4. Prefix : + A * B C

6. Prefix/Postfix Evaluation (Using Stack)

Postfix Evaluation:

  • Scan left to right
  • Push operands
  • On operator β†’ pop 2, apply, push result

Example: 5 6 + 2 *

Step 1: 5 β†’ push
Step 2: 6 β†’ push
Step 3: + β†’ pop 5, 6 β†’ push 11
Step 4: 2 β†’ push
Step 5: * β†’ pop 11, 2 β†’ push 22
Result = 22

Prefix Evaluation:

  • Scan right to left
  • Push operands
  • On operator β†’ pop 2, apply, push result

Example: * + 5 6 2

Step 1: 2 β†’ push
Step 2: 6 β†’ push
Step 3: 5 β†’ push
Step 4: + β†’ pop 5, 6 β†’ push 11
Step 5: * β†’ pop 11, 2 β†’ push 22
Result = 22

7. All Conversion Examples

InfixPostfixPrefix
A + BA B ++ A B
A + B * CA B C * ++ A * B C
(A + B) * CA B + C ** + A B C
A * (B + C) / DA B C + * D // * A + B C D

8. Applications

  • Compilers and Expression Parsing
  • Expression evaluation in calculators
  • Intermediate code generation
  • Abstract syntax trees