Interview question: How to convert inorder expressions into preorder expressions and postorder expressions

Inorder expressions are converted to preorder expressions and postorder expressions


Question: Convert inorder expressions to prefix expressions and postfix expressions, for example:
(a+b) c (de/f) Converted to prefix expressions: *-/fed*c+ba , converted to postfix expressions The formula is: ab+c*def/- *

Input: (a+b) c (de/f)

Output: prefix: *-/fed*c+ba, postfix expression is: ab+c*def/- *

Conversion rules for suffix expressions:
1. Operand encountered: direct output (added to the suffix expression)
2. When the stack is empty, when an operator is encountered, it is directly pushed onto the stack
3. When a left bracket is encountered: it is pushed onto the stack
4. When the right bracket is encountered: the pop operation is performed, and the popped element is output until the left bracket is popped from the stack, and the bracket is not output.
5. Encounter other operators: addition, subtraction, multiplication and division: pop all the top elements of the stack whose priority is greater than or equal to the operator, and then push the operator into the stack
6. Finally, the elements in the stack are popped out of the stack and output.

The conversion rule of prefix expression is: different from infix to suffix, infix expression to suffix expression reads each character in order from right to left, and then reverses the string.
There is also a more important problem: when an infix expression is converted to a postfix expression, when an operator is pushed onto the stack, the top element of the stack whose priority is greater than or equal to the operator will be popped;
while in the infix expression When the expression is converted to a prefix expression, the top element of the stack with a precedence greater than the operator is popped. And the order of parentheses will also return

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325502653&siteId=291194637