I’m making a program tasked with converting a math expression such as (2+4)*(4/3) into
a binary tree, and then manipulating it.
First, when parsing, i’ve turned the string into two stacks, operands and operators.
How can I determine what the root should be, given that in my example above the tree should look like this:
*
/ \
+ /
/\ /\
2 4 4 3
Notice that the root is * which is the outermost operand. But on my operand stack it looks like this:
/
*
+
And there could be cases like (2+4+3)*4 or 2*((4+1)/3).
How can I determine which operand should be the root of my binary tree?
Convert your infix expression to either prefix or postfix notation. You can’t really have a proper operator stack without doing this.
In postfix notation, the expression
(2+4)*(4/3)would look like:So, you have the multiplication appearing at the end which could be inserted into the tree as its root. Evaluating a postfix expression is much easier for a computer as grouping is not needed.