The idea: the shape of the tree is the order of work

An expression tree is a binary tree that holds an arithmetic expression. Each leaf is an operand (a number). Each inner node is an operator, and its two children are the two things it combines: the left child is the left operand, the right child is the right operand. The tree has no brackets and needs no precedence table. An operator lower in the tree is computed first, simply because its parent needs its value.

The tree for 3 + 4 * 2: + at the root, 3 as its left child, * as its right child with children 4 and 2. Next to it, the three ways to read it: pre-order gives + 3 * 4 2, in-order gives ( 3 + ( 4 * 2 ) ), post-order gives 3 4 2 * +.
One tree, three walks: pre-order prints prefix, in-order prints infix, post-order prints postfix.

This page builds the tree from a postfix or an infix expression, computes its value, and prints it in the three notations. It is the tree that Infix to Postfix never draws, and the same kind of tree a compiler's parser builds in Inside a Tiny Compiler.

Building from postfix with a stack of subtrees

Read the postfix left to right. Keep a stack of subtrees (really a stack of pointers to their roots).

  • An operand becomes a tree with one node. Push it.
  • An operator pops the top tree: that is its right operand. It pops the next tree: that is its left operand. It makes a new node with those two children and pushes the new tree.
  • At the end, the stack holds exactly one tree: the whole expression.

For 3 4 2 * +: push 3, push 4, push 2; * pops 2 (right) and 4 (left) and pushes 4*2; + pops 4*2 (right) and 3 (left) and pushes 3+(4*2). That is 5 nodes and height 2 (Demo: postfix 3 4 2 * +). The order of popping matters: for -, / and ^, swapping the children changes the value.

The subtree stack after each token of 3 4 2 * +: [3], [3, 4], [3, 4, 2], then * joins 4 and 2 so the stack is [3, 4*2], then + joins them into one tree 3+(4*2).
An operand pushes one tree; an operator turns the top two trees into one, so the stack shrinks by one.

On the canvas every node is drawn where it will sit in the finished tree: across by its in-order position, down by its depth. So a subtree on the stack is already in place, and a new operator node lands above its two children.

When the postfix is not valid

The stack also checks the input. Count operands as +1 and operators as -1 (each operator turns two trees into one). Two things can go wrong:

inputwhat happensmeaning
3 4 + ** finds one tree on the stack, not twostack underflow: too few operands
3 4 2 +the input ends with two trees, 3 and 4+2too few operators

A postfix list is valid exactly when the count never drops below 1 after an operator and ends at 1. (Demos: bad postfix 3 4 + *; bad postfix 3 4 2 +.)

Evaluating bottom-up

A leaf's value is its number. An operator node's value is left op right, and it can only be computed once both children have values. So evaluation is a post-order walk: left subtree, right subtree, then the node. In code it is a short recursive function:

value(node):
    if node is a leaf: return its number
    a = value(node.left)
    b = value(node.right)
    return a (node.op) b

For ( 5 - 1 ) * ( 2 + 6 ) / 4 the walk computes 5 - 1 = 4, 2 + 6 = 8, 4 * 8 = 32, then the root 32 / 4 = 8 (Demo: evaluate bottom-up). Each node is computed once, so it takes O(n) time. The page writes each value next to its node.

Three traversals, three notations

The three depth-first traversals of a binary tree differ only in when they write the node. On an expression tree each one prints a different notation:

traversalorderprintsfor (5-1)*(2+6)/4
pre-ordernode, left, rightprefix (Polish)/ * - 5 1 + 2 6 4
in-orderleft, node, rightinfix( ( ( 5 - 1 ) * ( 2 + 6 ) ) / 4 )
post-orderleft, right, nodepostfix (reverse Polish)5 1 - 2 6 + * 4 /

In-order alone loses information: 5 - 1 * 2 + 6 / 4 could come from many trees. So the in-order walk writes ( when it enters an operator node and ) when it leaves it. The result is fully bracketed and can be read with no precedence rules at all. Post-order gives back the postfix the tree was built from. (Demo: three traversals.) The same three walks over a search tree are on Binary Search Trees.

From infix: shunting-yard with a subtree stack

To build the tree straight from infix, run shunting-yard with two stacks. Operators and ( wait on the operator stack by precedence, exactly as there. Operands go onto the subtree stack as leaves. The one change: when an operator leaves the operator stack, it does not go to an output string. It pops two subtrees and pushes a new tree, as in the postfix build.

The operators leave the operator stack in postfix order, so this builds the same tree, node for node, as building from the postfix. For 3 + 4 * 2 the post-order walk prints 3 4 2 * + (Demo: from infix 3 + 4 * 2). At most 2 operators wait at once there, and at most 3 subtrees.

The shape shows associativity

Precedence and associativity decide the shape. Subtraction is left-associative: 8 - 3 - 2 is (8 - 3) - 2 = 3, so the tree leans left: the root's left child is the other -. Powers are right-associative: 2 ^ 3 ^ 2 is 2 ^ (3 ^ 2) = 512, so the tree leans right (Demos: left-assoc; right-assoc).

Left: the tree for 8 - 3 - 2 with - at the root, another - as the left child over 8 and 3, and 2 as the right child; value 3. Right: the tree for 2 ^ 3 ^ 2 with ^ at the root, 2 as the left child, and another ^ as the right child over 3 and 2; value 512.
Left-associative operators grow the tree down the left side; right-associative ones down the right side.

Which tree a grammar gives, and what happens when it allows two, is a question about grammars, covered in Grammar Ambiguity. Here the precedence table always picks one tree.

Cost

Each token is pushed and popped at most once, so building takes O(n) time. The tree has n nodes, and evaluating or printing it visits each node once: O(n). The recursion is as deep as the tree is high, which is n in the worst case (1 - 2 - 3 - 4 …). The stacks are ordinary array stacks; Recursion to an Explicit Stack shows how the recursive walks can use one too.

See also Grammar Ambiguity, where the grammar E → E + E | E * E | id gives 3 + 4 * 2 style input two trees and the E, T, F levels leave only one.

What the page leaves out

Multi-digit numbers and variable names (a tokenizer groups them), unary minus (a node with one child), function calls with many arguments (a node with many children), printing infix with only the brackets that are needed, simplifying a tree (x * 1 → x, constant folding), and the grammar view of the same tree.

On the mind map

Open the Indexing mind mapIndexingOrdered search: O(log n) by comparing keysOrdered searchHash tables: O(1) average, no orderHash tablesCaches: keep the hot keys closeCachesTries: walk the key one char at a timeTriesDisk trees: wide nodes, few disk readsDisk treesSpatial indexes: points near a placeSpatial indexesRange queries: sum of a range in O(log n)Range queriesSketches and sampling: small memory, approximate answerSketches and samplingLinear, binary searchLinear, binary searchsorted array: halve the range each probeBinary search treeBinary search treeleft smaller, right bigger; can go O(n)Expression treespost-order evaluates and prints postfixAVL treeAVL treeheights differ by at most 1; rotateRed-black treeRed-black treeno red-red, same black count on pathsAVL vs red-blackAVL vs red-blackAVL: faster reads; RB: fewer rotationsSplay treeSplay treemove each accessed key to the rootTreapTreapBST by key, heap by random prioritySkip listSkip listcoin-flip levels as express lanesPersistent treesPersistent treescopy the path, share the restInterval treeInterval treeeach node keeps the max end below it2-3-4 tree2-3-4 treea red-black tree in disguiseOrder-statistic treeOrder-statistic treesubtree sizes give rank and k-thOpen the Indexing mind mapIndexingO(log n) by comparing keysOrdered searchLinear, binary searchLinear, binary searchsorted array: halve the range each probeBinary search treeBinary search treeleft smaller, right bigger; can go O(n)Expression treespost-order evaluates and prints postfixAVL treeAVL treeheights differ by at most 1; rotateRed-black treeRed-black treeno red-red, same black count on pathsAVL vs red-blackAVL vs red-blackAVL: faster reads; RB: fewer rotationsSplay treeSplay treemove each accessed key to the rootTreapTreapBST by key, heap by random prioritySkip listSkip listcoin-flip levels as express lanesPersistent treesPersistent treescopy the path, share the restInterval treeInterval treeeach node keeps the max end below it2-3-4 tree2-3-4 treea red-black tree in disguiseOrder-statistic treeOrder-statistic treesubtree sizes give rank and k-th
This page on the Indexing mind map · 42 pages in 8 branches · open it to see the whole map and test yourself in recall mode.