🔄 Detailed conversion: step‑by‑step
We'll convert the infix expression: (A + B) * C - D / E (with precedence: * and / before + and -)
📌 1. Infix → Postfix (Shunting‑yard algorithm)
Rules: Scan left‑to‑right. Operands → output. Operators → stack (higher precedence pops first). Parentheses: ( push, ) pop until (.
| Step |
Symbol |
Stack |
Output |
Action |
| 1 | ( | ( | | push ( |
| 2 | A | ( | A | output operand |
| 3 | + | ( + | A | push + |
| 4 | B | ( + | A B | output operand |
| 5 | ) | | A B + | pop until ( → output + |
| 6 | * | * | A B + | push * |
| 7 | C | * | A B + C | output operand |
| 8 | - | - | A B + C * | * pops, push - |
| 9 | D | - | A B + C * D | output operand |
| 10 | / | - / | A B + C * D | push / |
| 11 | E | - / | A B + C * D E | output operand |
| 12 | end | | A B + C * D E / - | pop all → / then - |
✅ Postfix result: A B + C * D E / -
📌 2. Infix → Prefix (parse tree / pre‑order)
Method: Build expression tree, then pre‑order traversal (root → left → right).
Tree: - (root) → left * → left + → A B → right C → right / → D E
| Step |
Traverse |
Prefix output |
Explanation |
| 1 | root - | - | root operator |
| 2 | left * | - * | left subtree |
| 3 | left of * → + | - * + | left of * |
| 4 | left of + → A | - * + A | operand |
| 5 | right of + → B | - * + A B | operand |
| 6 | right of * → C | - * + A B C | operand |
| 7 | right of - → / | - * + A B C / | right subtree |
| 8 | left of / → D | - * + A B C / D | operand |
| 9 | right of / → E | - * + A B C / D E | operand |
✅ Prefix result: - * + A B C / D E
📌 3. Postfix ↔ Prefix (stack reversal)
Method: Reverse postfix, scan, and combine using a stack.
Postfix: A B + C * D E / - → Reverse: - / E D * C + B A
| Step |
Symbol |
Stack (prefix) |
Action |
| 1 | - | - | push operator |
| 2 | / | - / | push operator |
| 3 | E | - / E | push operand |
| 4 | D | - / E D | push operand |
| 5 | * | pop D,E → / D E, push * | combine |
| 6 | C | pop / D E and C → * / D E C | combine |
| 7 | + | pop * / D E C and B → + B * / D E C | combine |
| 8 | B | (already combined) | push operand |
| 9 | A | pop + B * / D E C and A → - A + B * / D E C | final combine |
✅ Prefix result: - * + A B C / D E
🧩 Summary for (A + B) * C - D / E:
Infix: (A + B) * C - D / E
Postfix: A B + C * D E / -
Prefix: - * + A B C / D E