# python数据结构与算法 9 中缀后前缀、后缀的转换思路

So far, we have used adhoc methods to convert between infix expressions and the equivalentprefix and postfix expression notations. As you might expect, there arealgorithmic ways to perform the conversion that allow any expression of anycomplexity to be correctly transformed.

The first technique that we willconsider uses the notion of a fully parenthesized expression that was discussedearlier. Recall that A + B * C can be written as (A + (B * C)) to showexplicitly that the multiplication has precedence over the addition. On closerobservation, however, you can see that each parenthesis pair also denotes thebeginning and the end of an operand pair with the corresponding operator in themiddle.

Look at the right parenthesis inthe subexpression (B * C) above. If we were to move the multiplication symbolto that position and remove the matching left parenthesis, giving us B C *, wewould in effect have converted the subexpression to postfix notation. If theaddition operator were also moved to its corresponding right parenthesisposition and the matching left parenthesis were removed, the complete postfixexpression would result (see Figure 6).

Figure 6: Moving Operators to theRight for Postfix Notation

If we do the same thing butinstead of moving the symbol to the position of the right parenthesis, we moveit to the left, we get prefix notation (see Figure 7). The position of the parenthesis pair is actually aclue to the final position of the enclosed operator.

Figure 7: Moving Operators to theLeft for Prefix Notation

So in order to convert anexpression, no matter how complex, to either prefix or postfix notation, fullyparenthesize the expression using the order of operations. Then move theenclosed operator to the position of either the left or the right parenthesisdepending on whether you want prefix or postfix notation.

Here is a more complexexpression: (A + B) * C - (D - E) * (F + G). Figure 8 shows the conversion to postfix and prefixnotations.

Figure 8: Converting a ComplexExpression to Prefix and Postfix Notations