Skip to main content

Convert expression to prefix and postfix

Short answer

Postfix: ABC*DE/F-G*-H*+. Prefix: +A*-*BC*-/DEFGH.

Convert the given infix expression (A+(B*C-(D/E-F)*G)*H) into equivalent prefix and postfix expressions showing each step in tabular form.

Infix: A + ( B * C − ( D / E − F ) * G ) * H.

Postfix (left to right)

StepSymbolStack (bottom → top)Postfix output
1A(empty)A
2++A
3(+(A
4B+(AB
5*+(*AB
6C+(*ABC
7-+(-ABC*
8(+(-(ABC*
9D+(-(ABC*D
10/+(-(/ABC*D
11E+(-(/ABC*DE
12-+(-(-ABC*DE/
13F+(-(-ABC*DE/F
14)+(-ABC*DE/F-
15*+(-*ABC*DE/F-
16G+(-*ABC*DE/F-G
17)+ABC*DE/F-G*-
18*+*ABC*DE/F-G*-
19H+*ABC*DE/F-G*-H
end(pop all)(empty)ABC*DE/F-G*-H*+

Postfix: ABC*DE/F-G*-H*+

Prefix

Reverse the infix string, swap ( and ), convert it like postfix (an incoming operator pops only operators of strictly higher precedence), then reverse the result.

Reversed with swapped brackets: H * ( G * ( F − E / D ) − C * B ) + A.

StepSymbol (reversed)StackOutput (before reversing)
1H(empty)H
2**H
3(*(H
4G*(HG
5**(*HG
6(*(*(HG
7F*(*(HGF
8-*(*(-HGF
9E*(*(-HGFE
10/*(*(-/HGFE
11D*(*(-/HGFED
12)*(*HGFED/-
13-*(-HGFED/-*
14C*(-HGFED/-*C
15**(-*HGFED/-*C
16B*(-*HGFED/-*CB
17)*HGFED/-*CB*-
18++HGFED/-*CB*-*
19A+HGFED/-*CB*-*A
end(pop all)(empty)HGFED/-*CB*-*A+

Reversing the output gives Prefix: +A*-*BC*-/DEFGH

Check: +A*-*BC*-/DEFGH read from the right with a stack gives the same expression tree as the postfix ABC*DE/F-G*-H*+.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 2 questions →