An arithmetic expression has operands (the values, like A or 7) and operators (+ - * / ^). There are three ways to write where an operator goes relative to its two operands — and stacks are how computers read and convert between them.
A + B. How people write maths.+ A B. The operator comes before its operands.A B +. The operator comes after its operands. Old HP calculators, the Java Virtual Machine and many compilers work this way.What is 2 + 3 * 4? It's 14, not 20 — but only because we agreed that * binds tighter than +. Infix can't be read left to right without knowing these precedence rules, and when you want the other order you need brackets: (2 + 3) * 4.
Prefix and postfix need neither precedence rules nor brackets. The position of each operator already says when it runs:
infix prefix postfix
2 + 3 * 4 + 2 * 3 4 2 3 4 * +
(2 + 3) * 4 * + 2 3 4 2 3 + 4 *
(A + B) * (C - D) * + A B - C D A B + C D - *Every expression is really a tree: operators are inner nodes and operands are leaves. The three notations are just three ways of walking the same tree:
That is why the conversions later in this course work: each one reads the tree out of one notation and writes it back in another. A stack holds the sub-trees that are finished but not yet attached to an operator.
A + B * C becomes (A + (B * C)).Postfix is the easiest notation for a computer to run. Scan left to right:
b, the second is the left operand a — and push a op b.Try 2 1 + 3 * — the operator always finds its two operands waiting on top.
Time O(n), space O(n) for n tokens. Order matters for - and /: in 5 3 -, the 3 is popped first, so it is b, and the answer is 5 - 3 = 2.
Prefix works the same way backwards: scan from the right, push numbers, and when you meet an operator the first pop is now the left operand.
function evalPrefix(tokens) { const stack = []; for (let i = tokens.length - 1; i >= 0; i--) { // right to left const t = tokens[i]; if (t === "+" || t === "-" || t === "*" || t === "/") { const a = stack.pop(); // reading backwards, the left operand is on top const b = stack.pop(); if (t === "+") stack.push(a + b); else if (t === "-") stack.push(a - b); else if (t === "*") stack.push(a * b); else stack.push(Math.trunc(a / b)); } else { stack.push(Number(t)); } } return stack.pop();}The interview questions Prefix to Infix, Prefix to Postfix and Postfix to Prefix use exactly this scan. The only change: instead of pushing numbers and computing, you push strings and glue them together — (A+B), AB+ or +AB.