Search code examples
algorithmdata-structurespostfix-mtaprefixinfix-notation

Operator associativity in prefix expression


I am going over infix, prefix and postfix conversions and I have a doubt regarding the following expression:

Infix: a+b*d-i
Below conversions are the ones I had in my mind. However, prefix expression below doesn't match with online conversion tools
Prefix: -+a*bdi
Postfix: abd*+i-

When I put the the above infix in some online converters or even in the code I wrote, I get:
Infix: a+b*d-i
Prefix: +a-*bdi
Postfix: abd*+i-

So, my question here is, if we're going to evaluate the above prefix then we'll be doing subtraction before the addition which seems incorrect to me as per operator associativity addition should be evaluated first. How is this correct?


Solution

  • The online converter you point to here uses an incorrect procedure for converting infix to prefix: https://www.web4college.com/converters/infix-to-postfix-prefix.php

    It says (and it's WRONG, so nobody copy this!):

    1. Reverse the infix string
    2. Convert to postfix
    3. Reverse the postfix string to get a prefix string

    The author of this is confused, because:

    • The postfix or prefix form of an expression is the postorder or preorder traversal of the expression tree; and
    • You can get the preorder traversal of a tree by reversing the postorder traversal of the reversed tree...

    BUT reversing an infix expression does NOT reverse its expression tree, because of left or right associativity. The given procedure therefore produces the wrong answer.

    a-b-c TREE      REVERSED TREE       c-b-a TREE
    
        -                 -                 -
       / \               / \               / \
      -   c             c   -             -   a
     / \                   / \           / \
    a   b                 b   a         c   b