Infix, prefix and postfix, and why postfix needs no brackets
1 One line, two meanings
We usually write each operator between its two numbers, as in 8 - 3 * 2. This is infix notation. The line alone does not say which operation comes first, and it fits two different calculations:
Each drawing is an expression tree. A number is a leaf. An operator is a node, and its two children are the values it works on, its operands. We work from the leaves up, so each operator runs once both its children are done. A tree has only one meaning.
Infix needs extra rules to say which tree it means:
- Precedence.
*and/go before+and-. So8 - 3 * 2is the second tree, and its value is 2. - Brackets. To mean the first tree, we must write
(8 - 3) * 2. - Left to right for equal precedence.
8 - 3 - 2is (8 − 3) − 2 = 3, not 8 − (3 − 2) = 7. This is left-associativity.
A program that reads infix has to apply all three rules. Two other ways of writing a tree need none of them.
2 One tree, three ways to read it
Our running example is (8 - 3) * 2 + 6 / 3. Its tree:
Each notation is a rule for walking this tree and writing down what we meet. At every operator, we write its left side, its right side and the operator itself. The three notations differ only in where the operator goes:
| Notation | The operator goes | Our expression |
|---|---|---|
| Infix | between its two sides | (8 - 3) * 2 + 6 / 3 |
| Prefix | before both sides | + * - 8 3 2 / 6 3 |
| Postfix | after both sides | 8 3 - 2 * 6 3 / + |
In postfix, the + at the top writes its whole left side first, 8 3 - 2 *. Then it writes its whole right side, 6 3 /, and then itself. Each side follows the same rule inside it.
The numbers 8, 3, 2, 6, 3 come in the same order in all three forms. Only the operators move. Prefix is also called Polish notation, and postfix reverse Polish notation (RPN). A later lesson on trees gives these walks their names: inorder, preorder and postorder.
Only infix needs brackets. Without them, 8 - 3 * 2 + 6 / 3 is a different tree, with value 4.
3 Postfix runs in reading order
In postfix, each operator comes right after both its operands are complete. So when we reach an operator, its two values are the last two we have worked out. The order of the tokens is the order of the work: 8 − 3 first, then × 2, then 6 / 3, then the +. No operator waits for a later one, so postfix needs no precedence rules and no brackets.
Infix is different. After reading 8 - 3, we cannot work it out yet, because a * 2 might come next and bind tighter.
"The last two values" is a job for a stack. We read the tokens from left to right:
- A number. Push it.
- An operator. Pop two values, apply the operator, and push the result.
The same run as a table:
| i | token | work | stack after |
|---|---|---|---|
| 0 | 8 | push | 8 |
| 1 | 3 | push | 8 3 |
| 2 | - | 8 − 3 = 5 | 5 |
| 3 | 2 | push | 5 2 |
| 4 | * | 5 × 2 = 10 | 10 |
| 5 | 6 | push | 10 6 |
| 6 | 3 | push | 10 6 3 |
| 7 | / | 6 / 3 = 2 | 10 2 |
| 8 | + | 10 + 2 = 12 | 12 |
Each value on the stack is one finished part of the tree. At i = 6, the 10 is the whole left side of the +. It waits at the bottom while the right side, 6 / 3, is worked out above it. At the end, the one value left is the answer.
The first pop is the right operand. At the -, the stack holds 8 and then 3, with 3 on top. The first pop gives 3, the right side. The second pop gives 8, the left side. So the result is 8 − 3 = 5, and swapping them gives −5.
4 The code and its cost
LeetCode's Evaluate Reverse Polish Notation gives the postfix tokens as strings and asks for the value. Division truncates toward zero. We name the two pops right and left, so the order stays clear.
C++
Division is already right. / on two ints truncates toward zero, so 7 / −2 gives −3.
Division is already right. / on two ints truncates toward zero, so 7 / −2 gives −3.
Do not use //. It rounds down, so 7 // -2 gives −4. int(left / right) divides as a decimal and then cuts toward zero, which gives −3.
Truncate by hand. / gives a decimal, −3.5 for 7 / −2. Math.trunc cuts it toward zero, to −3. Math.floor would give −4.
Division is already right. / on two ints truncates toward zero, so 7 / −2 gives −3.
Division is already right. / on two i32s truncates toward zero, so 7 / −2 gives −3.
Division is already right. / on two ints truncates toward zero, so 7 / −2 gives −3.
Every tab returns 12 for our tokens, 2 for 8 3 2 * -, and −3 for 7 -2 /.
Each token is one push, or two pops and a push, so the pass is O(n) for n tokens. When all the numbers come first, as in 1 2 3 4 + + +, about half the tokens sit on the stack at once. So the space is O(n).
5 Prefix, and turning one form into another
Read from right to left, prefix puts the operands before each operator, just as postfix does. So the same loop evaluates prefix, run from the last token to the first. One thing flips: the left operand is now pushed last, so the first pop is the left operand.
On + * - 8 3 2 / 6 3, read from the right:
| token | work | stack after |
|---|---|---|
| 3 | push | 3 |
| 6 | push | 3 6 |
| / | 6 / 3 = 2 | 2 |
| 2 | push | 2 2 |
| 3 | push | 2 2 3 |
| 8 | push | 2 2 3 8 |
| - | 8 − 3 = 5 | 2 2 5 |
| * | 5 × 2 = 10 | 2 10 |
| + | 10 + 2 = 12 | 12 |
The same loop also turns one form into another. The stack holds strings instead of numbers, and each string is one finished part of the tree, written in the new form. At an operator, we pop two strings and push them joined:
| Converting | Read | At an operator, push |
|---|---|---|
| Postfix to infix | left to right | (left op right) |
| Postfix to prefix | left to right | op left right |
| Prefix to infix | right to left | (left op right) |
| Prefix to postfix | right to left | left right op |
Our postfix 8 3 - 2 * 6 3 / + turns into infix like this, one row per operator:
| token | stack after |
|---|---|
| - | (8 - 3) |
| * | ((8 - 3) * 2) |
| / | ((8 - 3) * 2), (6 / 3) |
| + | (((8 - 3) * 2) + (6 / 3)) |
The result has brackets around every operator. It never relies on precedence, and it is the form these problems usually expect. Each join copies both strings, so a long chain like 1 2 + 3 + 4 + … copies O(n²) characters in all.
6 Infix to postfix with an operator stack
Infix to postfix is the hard direction, because infix leans on precedence and brackets. The numbers keep their order in every form, so each number goes straight to the output. The work is deciding when each operator goes out.
Operators wait on a stack. A waiting operator goes out when a new one arrives and binds no tighter than it. This is the shunting-yard algorithm. For each token:
- A number. Write it to the output.
(. Push it. It walls off the operators below it.). Pop operators to the output until the(, then drop the(.- An operator. While the top of the stack is an operator of higher or equal precedence, pop it to the output. Then push the new one.
- The end. Pop everything left to the output.
The "equal" in the operator rule is left-associativity. In 8 - 3 - 2, the first - must run first, so it goes out when the second one arrives.
Every token, as a table:
| token | action | operators | output |
|---|---|---|---|
| ( | push | ( | |
| 8 | output | ( | 8 |
| - | push | ( - | 8 |
| 3 | output | ( - | 8 3 |
| ) | pop to the ( | 8 3 - | |
| * | push | * | 8 3 - |
| 2 | output | * | 8 3 - 2 |
| + | pop *, push + | + | 8 3 - 2 * |
| 6 | output | + | 8 3 - 2 * 6 |
| / | push | + / | 8 3 - 2 * 6 |
| 3 | output | + / | 8 3 - 2 * 6 3 |
| end | pop all | 8 3 - 2 * 6 3 / + |
The output is the postfix from section 2. The stack rebuilt the tree's order of work without drawing the tree. Each operator is pushed once and popped once, so this is O(n) time, with O(n) space for the stack.
Infix to prefix takes one more step: infix to postfix, then postfix to prefix with the stack of strings. A common shortcut reverses the tokens, swaps the brackets, runs the same loop and reverses the output. In that run, an operator of equal precedence must stay on the stack, or 8 - 3 - 2 comes out as 8 − (3 − 2).
7 Mistakes and edge cases
- Swapped operands. Taking the first pop as the left operand turns
8 3 -into −5 instead of 5.+and*give the same answer either way, so the bug hides until a-or/shows up. - Division that rounds down. On
7 -2 /, the answer is −3, truncated toward zero. Rounding down gives −4. The note under the code says what your language does. - A negative number taken for an operator. In
7 -2 /, the token-2is a number. A check on the first character alone treats it as a minus. The code compares the whole token with"-". - Numbers longer than one digit. In a string such as
"12+3*45", a number spans several characters. We keep reading digits and build the whole number before the next token. - Right-associative
^. Power runs from right to left:2 ^ 3 ^ 2is 2⁹ = 512, not 8² = 64. In shunting-yard, a^on the stack must stay when another^arrives. Popping it gives2 3 ^ 2 ^, which is 64. The right postfix is2 3 2 ^ ^.
8 When to use it
The sign is an expression in one notation that has to be worked out or written in another. The input's form picks the tool:
- Postfix or prefix to evaluate. One stack of numbers and one pass. Prefix reads from the right.
- Postfix or prefix to any other form. The same pass with a stack of strings.
- Infix in. Shunting-yard first, to get postfix. A calculator that evaluates infix directly runs the same two stacks at once: numbers on one, operators on the other.
The next lesson uses the stack in a new way. It keeps the values on the stack in sorted order, to find the next greater value for each element.
Practice it
- Infix to postfixMedium
- Infix to prefixMedium
- Postfix to infixMedium
- Prefix to infixMedium
- Prefix to postfixMedium
- Postfix to prefixMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.