Answer the question
In order to leave comments, you need to log in
How to get an AST tree from Polish notation?
The task is algorithmic and without reference to any language. At the input, reverse Polish notation includes left-associative operators, functions with an arbitrary number of parameters, and numbers. At the output, you need to get an AST tree. Any references and answers in the style of "mine was in such and such a book" are welcome.
Answer the question
In order to leave comments, you need to log in
sequentially read the expression, for each lexeme according to its type:
number -> create a node (NUMBER, value), put it on the stack;
unary operator -> remove a node (child) from the stack, create a node (UNARY OPERATION, type, child), put a new node on the stack;
binary operator -> remove two nodes from the stack (child1 and child2), create a node (BINARYOPERATION, type, child1, child2), put a new node on the stack;
function -> remove N nodes from the stack according to the number of function arguments (child1,... descendantN), create a node (FUNCTION, name, descendant1,... descendantN), put a new node on the stack;
At the end of the work on the correct expression, one node should lie on the stack, and it will be the root of the tree.
At the input, reverse Polish notation includes operators, functions, brackets and numbers.
It is not entirely clear why there are brackets in Polish notation, and what they can mean in it.
For a regular Polish notation with operators and numbers, you can simply use the algorithm for calculating it. Only the result of the operations will not be values, but subtrees.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question