First of all, sorry for my bad English.
For my last project on my Algorithms and Data Structures class, I need to create a simple numerical expression solver in C++. It needs to solve simple expressions like 3*12+(4-6). I managed to split the expression and separate the operators from the numbers, but I can't go any further. The trick is putting the operators on a binary tree, but I haven't managed to do that.
The program needs to use only the default C++ libs. Maybe there is some basic implementation I can build on?
Thanks in advance.
Forget binary trees for a moment.
You need to convert the expression into reverse polish notation. During that conversion you are constructing a binary tree!
[Reverse polish notation][2]
Look at this http://www.codeproject.com/KB/recipes/rwformulaparser.aspx I think this project will solve your problem Josemi
You will want to convert it into reverse polish notation, the algorithm for the conversion is a little complicated, but many websites detail the exact steps. Doing multi-digit numbers will make it a little more complicated.
The most important thing you need to know is that for RPN, you will have to use a stack, not a binary tree. Once an equation is switched to RPN, you will empty it's numbers into a stack until you run into a operator, where you will then take the top two numbers from the stack and do the operation on them and put that final value back onto the stack. In the end you will be left with one number on the stack and it will be the answer to your equation.
来源:https://stackoverflow.com/questions/11162902/simple-numerical-expression-solver