Algorithm: Infix, Prefix and Postfix Traversal
1. Notations Overview
| Notation | Format Example | Operator Position |
|---|---|---|
| Infix | A + B | Between operands |
| Prefix | + A B | Before operands |
| Postfix | A 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
| Operator | Precedence | Associativity |
|---|---|---|
^ | 3 | Right to Left |
* / % | 2 | Left to Right |
+ - | 1 | Left to Right |
4. Infix to Postfix Conversion (Using Stack)
Steps:
- If operand β add to output
- If
(β push to stack - If
)β pop till( - 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:
- Reverse infix string
- Replace
(with), and vice versa - Convert to postfix
- Reverse result β itβs prefix
Example: A + B * C
1. Reverse: C * B + A2. Postfix: C B * A +3. Reverse: + A * B C4. Prefix : + A * B C6. 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 β pushStep 2: 6 β pushStep 3: + β pop 5, 6 β push 11Step 4: 2 β pushStep 5: * β pop 11, 2 β push 22Result = 22Prefix Evaluation:
- Scan right to left
- Push operands
- On operator β pop 2, apply, push result
Example: * + 5 6 2
Step 1: 2 β pushStep 2: 6 β pushStep 3: 5 β pushStep 4: + β pop 5, 6 β push 11Step 5: * β pop 11, 2 β push 22Result = 227. All Conversion Examples
| Infix | Postfix | Prefix |
|---|---|---|
| A + B | A B + | + A B |
| A + B * C | A B C * + | + A * B C |
| (A + B) * C | A B + C * | * + A B C |
| A * (B + C) / D | A B C + * D / | / * A + B C D |
8. Applications
- Compilers and Expression Parsing
- Expression evaluation in calculators
- Intermediate code generation
- Abstract syntax trees