Infix to Postfix

901 Views Asked by At

4 + x / b - a + 5 AND x AND y OR p OR q

What is the tree and the postfix of the expression above?

I find it tricky because I am not sure if AND has higher precedence than the arithmetic operators, maybe OR does.

EDIT: I didn't realize that depending on the context AND could have lower precedence than multiplication for example. So lets assume that this is a code in Java.

if(4 + x / b - a + 5 AND x AND y OR p OR q)

How does this expression look like in post order to the computer? If I am not mistaken this would mean that the order of operations is

* / 
+ -
AND
OR

Someone correct me if you know better. If that order above is correct then the answer is: $$4xb/+ a - 5 + x AND y AND p OR q OR$$

or

$$xb/4+a-5+xANDyANDpqOROR$$

Both should yield the same result, it is just a matter of how you write it, I think.

1

There are 1 best solutions below

2
On BEST ANSWER

Given the hierarchy that you think is correct for Java and left-to-right evaluation within a level, your expression becomes

$$\left[\left(\left[\left(\bigg[\left(\Big[4+(x/b)\Big]-a\right)+5\bigg]\text{ AND }x\right)\text{ AND }y\right]\text{ OR }p\right)\text{ OR }q\right]$$

when fully parenthesized. The associated tree:

                                                              OR  
                                                            /    \  
                                                         OR        q  
                                                       /    \  
                                                    AND       p  
                                                  /     \  
                                               AND        y  
                                             /     \  
                                           +         x  
                                         /   \  
                                       -       5  
                                     /   \  
                                   +       a  
                                 /   \  
                               4       ÷  
                                     /   \  
                                   x       b

And you can read off the postfix string as:

                    4 x b / + a - 5 + x AND y AND p OR q OR