Infix / prefix / postfix
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
These are three ways to write the same calculation. Infix is the usual "3 + 4", prefix puts the operator first "+ 3 4", and postfix puts it last "3 4 +". Postfix and prefix need no brackets and no rules about which operator goes first, which makes them easy for programs to evaluate.
Practical use cases
- Web app: How a calculator app reads 3 + 4 * 2. A calculator in the browser must answer 11, not 14, because multiplication goes first. Rather than guessing, it converts what the user typed into postfix, "3 4 2 * +", where the order of work is already visible. Evaluating that form is then a simple left-to-right pass with a stack.
- Web app: A discount rule typed by a shop owner. A shop admin types a rule like price - (price * 10) / 100 into a settings box. The app converts it to postfix once and stores it. At checkout it evaluates the stored form quickly for every cart, with no need to re-read the brackets.
- System: Compilers and stack machines. Compilers turn the formulas in source code into a form with an explicit order of work, often like postfix. Some virtual machines, like the one that runs Java bytecode, are stack machines which run postfix style instructions directly, which keeps the machine simple and the programs small.
The story: Zoya's Bill Without Brackets
Zoya helped her uncle at the kirana store. One afternoon the old calculator broke, and a customer's bill read 2 + 3 * 4: two packets at one price, plus three of something that cost four rupees each. Uncle said 20. Zoya said 14. They both did the sums right, but in a different order!
Zoya remembered Mrs. Sharma's rule: "multiply comes before add". Uncle had simply added first. The way we normally write maths, with the operator in between the numbers, hides the order. That is why we also need brackets, and a rule book.
Mrs. Sharma showed a cleverer way. "Put the operator after the numbers it works on." So 3 * 4 becomes 3 4 *, and the whole bill is 2 3 4 * +. Read from left to right, it says exactly what to do: take 3 and 4, multiply them, then add 2. No rule book, no brackets, no argument.
The ordinary style is called infix, the after-style is postfix (also called Reverse Polish Notation), and putting the operator before is prefix. Computers love postfix because a stack can handle it, as you will see soon.
How to spot this problem, and where you need it
A formula typed by a person has brackets and operator rules, such as multiplication before addition, and the program needs an unambiguous form that is easy to compute.
Signs you need it
- Users can type their own formulas or rules in a settings page, a spreadsheet cell or a pricing rule editor.
- Your code is full of special cases for brackets and operator precedence and still gets some answers wrong.
- The problem statement talks about "postfix", "prefix", "reverse Polish" or "evaluate an expression".
Where to use it in a project
- Calculators, spreadsheets and pricing or discount rule engines.
- Search query parsers that handle AND, OR and brackets.
- Compilers, interpreters and scripting features in an application.
The solution
Convert the human-friendly infix expression into postfix, where each operator appears after its two numbers. Then the order of work is fixed and brackets are no longer needed. Evaluate the postfix form from left to right with a stack of numbers. You can convert once and reuse the postfix form many times.
Payoff: Before: tangled bracket and precedence checks with wrong answers. After: one clean conversion and a simple evaluation loop that is right every time.
Explain it like I am 8
Say "three plus four". The word "plus" sits in the middle: that is infix. Now say "plus three four". The operator comes first: that is prefix. Say "three four plus". The operator comes last: that is postfix. The meaning is the same, but only the first one needs brackets to stay clear!
How it works, step by step
- Infix: operator between the two operands (
3 + 4). It needs precedence rules and brackets. - Prefix: operator before its operands (
+ 3 4). Also called Polish notation. - Postfix: operator after its operands (
3 4 +). Also called Reverse Polish notation. - Operands keep their order in all three styles. Only the operators move around.
- Prefix and postfix need no brackets: the position of the operator already says what it applies to.
The code in four languages
PHP
<?php
// An expression tree: [operator, left, right]. Numbers are leaves.
// The three notations are just three ways of walking the same tree.
$tree = ['*', ['+', 2, 3], 4]; // (2 + 3) * 4
function infix(array|int $n): string {
if (is_int($n)) return (string)$n;
return '(' . infix($n[1]) . ' ' . $n[0] . ' ' . infix($n[2]) . ')'; // left op right
}
function prefix(array|int $n): string {
if (is_int($n)) return (string)$n;
return $n[0] . ' ' . prefix($n[1]) . ' ' . prefix($n[2]); // op left right
}
function postfix(array|int $n): string {
if (is_int($n)) return (string)$n;
return postfix($n[1]) . ' ' . postfix($n[2]) . ' ' . $n[0]; // left right op
}
echo infix($tree) . PHP_EOL; // ((2 + 3) * 4)
echo prefix($tree) . PHP_EOL; // * + 2 3 4
echo postfix($tree) . PHP_EOL; // 2 3 + 4 *JavaScript
// An expression tree: [operator, left, right]. Numbers are leaves.
// The three notations are just three ways of walking the same tree.
const tree = ['*', ['+', 2, 3], 4]; // (2 + 3) * 4
function infix(n) {
if (typeof n === 'number') return String(n);
return '(' + infix(n[1]) + ' ' + n[0] + ' ' + infix(n[2]) + ')'; // left op right
}
function prefix(n) {
if (typeof n === 'number') return String(n);
return n[0] + ' ' + prefix(n[1]) + ' ' + prefix(n[2]); // op left right
}
function postfix(n) {
if (typeof n === 'number') return String(n);
return postfix(n[1]) + ' ' + postfix(n[2]) + ' ' + n[0]; // left right op
}
console.log(infix(tree)); // ((2 + 3) * 4)
console.log(prefix(tree)); // * + 2 3 4
console.log(postfix(tree)); // 2 3 + 4 *Java
public class Main {
// An expression tree: a node is either a number (leaf) or an operator with two children.
// The three notations are just three ways of walking the same tree.
interface Expr {}
record Num(int value) implements Expr {}
record Op(String op, Expr left, Expr right) implements Expr {}
static String infix(Expr n) {
if (n instanceof Num num) return String.valueOf(num.value());
Op o = (Op) n;
return "(" + infix(o.left()) + " " + o.op() + " " + infix(o.right()) + ")"; // left op right
}
static String prefix(Expr n) {
if (n instanceof Num num) return String.valueOf(num.value());
Op o = (Op) n;
return o.op() + " " + prefix(o.left()) + " " + prefix(o.right()); // op left right
}
static String postfix(Expr n) {
if (n instanceof Num num) return String.valueOf(num.value());
Op o = (Op) n;
return postfix(o.left()) + " " + postfix(o.right()) + " " + o.op(); // left right op
}
public static void main(String[] args) {
Expr tree = new Op("*", new Op("+", new Num(2), new Num(3)), new Num(4)); // (2 + 3) * 4
System.out.println(infix(tree)); // ((2 + 3) * 4)
System.out.println(prefix(tree)); // * + 2 3 4
System.out.println(postfix(tree)); // 2 3 + 4 *
}
}Go
package main
import (
"fmt"
"strconv"
)
// Expr is a node of an expression tree: a number (leaf) or an operator with two children.
// The three notations are just three ways of walking the same tree.
type Expr struct {
op string // empty for a number
num int
left, right *Expr
}
func number(n int) *Expr { return &Expr{num: n} }
func operator(op string, l, r *Expr) *Expr {
return &Expr{op: op, left: l, right: r}
}
func infix(n *Expr) string {
if n.op == "" {
return strconv.Itoa(n.num)
}
return "(" + infix(n.left) + " " + n.op + " " + infix(n.right) + ")" // left op right
}
func prefix(n *Expr) string {
if n.op == "" {
return strconv.Itoa(n.num)
}
return n.op + " " + prefix(n.left) + " " + prefix(n.right) // op left right
}
func postfix(n *Expr) string {
if n.op == "" {
return strconv.Itoa(n.num)
}
return postfix(n.left) + " " + postfix(n.right) + " " + n.op // left right op
}
func main() {
tree := operator("*", operator("+", number(2), number(3)), number(4)) // (2 + 3) * 4
fmt.Println(infix(tree)) // ((2 + 3) * 4)
fmt.Println(prefix(tree)) // * + 2 3 4
fmt.Println(postfix(tree)) // 2 3 + 4 *
}Time: O(n) · Extra space: O(n). Writing any of the three forms visits each number and operator once. The recursion needs room as deep as the expression is nested.
Watch out for
- Thinking prefix is postfix reversed character by character. The operands stay in the same order; only the operators move.
- Adding brackets to prefix or postfix. They are never needed, and that is the whole point.
- Forgetting that for - and / the order of operands matters:
5 3 -is 2, but3 5 -is -2.
Quick check
- Which is the postfix form of 3 + 4?
- 3 4 +
- 3 + 4
- + 3 4
- Which style needs brackets to show the order of work?
- Postfix
- Infix
- Prefix
- What is the prefix form of 2 + 3 * 4?
- * + 2 3 4
- 2 3 4 * +
- + 2 * 3 4