Could someone explain how to build a binary expression tree.
For example I have a string 2*(1+(2*1));
How to convert this into a binary expression tree.
*
| \
| \
2 +
|\
1 *
|\
2 1
Could someone explain how to build a binary expression tree.
For example I have a string 2*(1+(2*1));
How to convert this into a binary expression tree.
*
| \
| \
2 +
|\
1 *
|\
2 1
Convert infix to postfix or prefix
The postfix input is: a b + c d e +**
Java Implementation
More info: http://en.wikipedia.org/wiki/Binary_expression_tree
you will need to:
for example, take a look at this approach: http://en.wikipedia.org/wiki/Recursive_descent_parser
there are others
Convert the expression to prefix or postfix notation. From there it should be pretty straightforward. Algorithms are mentioned in the following wiki links.
http://en.wikipedia.org/wiki/Polish_notation
http://en.wikipedia.org/wiki/Reverse_Polish_notation
It can be divided into two steps:
Calculate priority value for each token.
For example: '+': 1, 'x': 2, number: inf, '(': add 10 to base, ')': subtract 10 from base)
Build Cartesian tree based on priority by using a stack (approx 5 lines of code)
You can do it in one scan.