creating a Binary tree based on a prefix expression

13.7k Views Asked by At

I want to find the value of a the prefix expression -/+8,10,2*3,2 and build its binary tree I am trying to learn this for a math course, but have absolutely no clue how to do it. Any help would be awesome!

2

There are 2 best solutions below

2
On

Hint: Think of a binary operator as a function whose two inputs are the next two numbers that come directly to the right of it. That is, if we define the following functions: \begin{align*} s(x,y) &= x-y \\ d(x,y) &= x/y \\ a(x,y) &= x+y \\ m(x,y) &= x*y \\ \end{align*}

then you can interpret the prefix expression to be:

$$ s\left(d \left( a \left(8, 10 \right), 2\right), m\left(3 , 2 \right) \right) $$

0
On

You can even Try using stack to solve it which is much more easy than the binary tree. In-fact the expression tree is just other form of representation However OS internally invokes stack to compute the result on the real machine.. For you i have mentioned both . Please feel free to ask if you get any more doubt and/or any other doubt in Data structures or related field.

And Yes the Answer is 3.

https://www.facebook.com/bewithjitendrapatel