2

I have to draw binary tree for this expression A*(B-C+D)*P/Q

Is this one correct?

                        *

             *                    /

          A     +              P     Q

              -   D 

            B   C
0

4 Answers 4

3

Your tree is corresponding to this expression:

   (A*(B-C+D))*(P/Q)

While technically correct, it should be like this (if you assume multiplication and division have equal precedence):

   ((A*(B-C+D))*P)/Q
Sign up to request clarification or add additional context in comments.

1 Comment

Your expression is still ambiguous, namely the B-C+D part.
1

Your answer is correct. Below are the steps to get this tree

A*(B-C+D)*P/Q

Step 1: As parentheses has maximum priority so its evaluated first.

B-C+D

But + and - has same execution priority so associativity is considered. The operators have same associativity Left to Right i.e left side must have only one operand to the operator. Only - operator has one operand to its left so it's excecuted first and then + So expression changes to

( (B-C) + D )

A*Z*P/Q where z=( (B-C) + D )

Step 2: * and / has same priority of evaluation, so to break the tie associativity of * and / is considered. Both the operator has same associativity Left to Right i.e left side must be unambiguous which implies that on left side of operator(* OR /) must has only one operand.

So only first * has one operand i.e A Hence A*Z is executed next

(A*Z)*P/Q

let us rename it to

AZ*P/Q

Step 3: Now following the associativity rule as remaining operand has same priority * is executed first as it has only one operand on its left AZ so,

AZP/Q

Step 4: finally / operator will be execute

AZPQ

Comments

0

I think You have made a mistake while writing expression .. According to me it would be A*B-(C+D)*P/Q And for this the Binary tree would be like this ..

                -
        *                    *
      A   B             +          /
                      C   D      P   Q

2 Comments

Are you the professor? If not, you don't get to up and change the expression.
Well I have brief knowledge about this and I am a Software Developer
0

To be unambiguous, the expression tree could have brackets around each binary operation. So that would result in different trees for (B- C) +D and B - (C + D) , though the result would be the same due to the associative rule of addition.

While there's less clarity for human reader, the advantage of consistent bracketing is to clearly distinguish (((A*(B-(C+D)))P)/Q) from ((A(B-(C+D)))*(P/Q)).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.