How to put postfix expressions in a binary tree?

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

[/] / \ [*] [3] / \ [6] [2] 
+7
source share
2 answers

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.

+15
source
 Postfix-to-tree(j){ n <--ALLOCATE_NODE(A[j],NULL,NULL) Switch case Postfix[j] is a binary operator do j <--j-1 right[n] <-- Postfix-to-tree(j) j <-- j-1 left[n] <--postfix-to-tree(j) case postfix[j] is a unary operator do j <-- j-1 right[n] <-- Postfix-to-tree(j) } 
0
source

Source: https://habr.com/ru/post/903048/


All Articles