To build a tree from an expression, pretend that you evaluate it directly, but create trees instead of calculating numbers. (This trick works for many other things besides postfix expressions.)
Algorithm: Has a stack for storing intermediate values (which are trees) and checks each token from left to right:
- If this is a number, turn it into a node sheet and click on it on the stack.
- If this is an operator, put two elements from the stack, build a node operator with these children and push the new node on the stack.
In the end, if the expression is correctly formed, you should have exactly one tree on the stack, which is the whole expression in the form of a tree.
source share