Table of contents
Prefix and middle suffix expression in formula in data structure - application of binary tree
Prefix and middle suffix expression in formula in data structure - application of binary tree
What are prefix expressions, infix expressions, and postfix expressions
Prefix expressions, infix expressions, and postfix expressions are three different ways to store and calculate expressions through trees
Take the following formula as an example
The formula is stored in a tree, which can be expressed as
Then the problem comes, the tree is just an abstract data structure, it must be stored and input through some form of text
At this point, there are three representation methods: prefix expression, infix expression, postfix expression
They are respectively equivalent to the pre-order traversal, middle-order traversal, and post-order traversal of the tree. The front, middle, and back refer to the traversal order of symbols during traversal.
Preorder traversal: symbol - left operand - right operand
Inorder traversal: left operand - sign - right operand
Post-order traversal: left operand - right operand - symbol
infix expression
The above formula, the result of inorder traversal is
Obviously, this expression is ambiguous. For example, ab is a subtree, cd is a subtree, and finally subtracted. The traversal result is the same as above
Therefore, infix expressions must use parentheses to correctly express the desired result
The expression result of the infix expression is
This expression is in line with human reading habits
prefix expression
The above formula, the result of preorder traversal is
This expression is unambiguous and can be directly used as the result of the prefix expression
This expression is in line with the computer's processing habits, and the program can easily parse this expression
Specifically how to parse, the code will be given below
postfix expression
The above formula, the result of post-order traversal is
This expression is also in line with the computer's processing habits, and the analysis is also very simple
Compared with prefix expressions, the symbol reading order of suffix expressions is consistent with human reading habits
Therefore, in actual computer programs, suffix expressions are basically used to store formulas, followed by prefix expressions
For infix expressions, we can convert them to postfix expressions first, and then evaluate them