Search code examples
algorithmtreeprefixpostfix-notation

Is it possible to construct a tree of postfix or prefix form?


Let I have some expression as 2*3/(2-1) +5*(4-1) . It is infix notation. Of course I can construct for this expression a tree that you can see on image. enter image description here

Then, let's write this expression in postfix and prefix forms. Postfix: 2 3 * 2 1 - / 5 4 1 - * + Prefix : + / * 2 3 - 2 1 * 5 - 4 1

And the question is: a tree for above expressions will be the same? If not,how to construct it?


Solution

  • And the question is: a tree for above expressions will be the same?

    Yes, it's the same tree -- the different notations represent the same calculation.


    The different ways to write the expression correspond just to different traversals of the same tree:

    • pre-order for prefix notation

    enter image description here

    (pre-order: F, B, A, D, C, E, G, I, H)

    • in-order for infix notation

    enter image description here

    (in-order: A, B, C, D, E, F, G, H, I)

    • post-order for postfix notation

    enter image description here

    (post-order: A, C, E, D, B, H, I, G, F)