Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put postfix expressions in a binary tree?

so i have a binary tree and a postfix expression "6 2 * 3 /" what is the algo to put it in a tree? like,

          [/]
          / \
        [*]  [3]
        / \
      [6] [2]
like image 371
Mudasir Soomro Avatar asked Dec 04 '11 14:12

Mudasir Soomro


People also ask

What is postfix expression of A +( B * C?

A + B * C would be written as + A * B C in prefix. The multiplication operator comes immediately before the operands B and C, denoting that * has precedence over +. The addition operator then appears before the A and the result of the multiplication. In postfix, the expression would be A B C * +.


1 Answers

To construct a tree from the expression, pretend you are evaluating it directly but construct trees instead of calculating numbers. (This trick works for many more things than postfix expressions.)

Algorithm: Have a stack to store intermediate values (which are trees), and examine each token from left to right:

  • If it is a number, turn it into a leaf node and push it on the stack.
  • If it is an operator, pop two items from the stack, construct an operator node with those children, and push the new node on the stack.

At the end, if the expression is properly formed, then you should have exactly one tree on the stack which is the entire expression in tree form.

like image 90
Kevin Reid Avatar answered Sep 16 '22 18:09

Kevin Reid