I have two stacks, one with operands, the other with operators. My problem is turning these two stacks into a binary tree.
For example, the expression (2+3)*(4-3)
will be translated into postfix ( such that 24+43-*
) and then put into two stacks
3442
and *-+
will be the stacks (with the tops being 3 and * respectively).
Now with these stacks, i need to form a binary tree like
*
+ -
2 3 4 3
Is there a way to do this recursively?
Right now, I have an algorithm like so:
Create the root of the tree, assign the value of the root to the first operator in the operator-stack. Set the right and left pointers to null.
Create the right node, assign the value of the next operator if it exists, if not assign it an operand. Then do the same for the left node.
My problem is making this recursive, or getting it to handle the many different cases.
Thanks for your help.