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.
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.
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:
| input | what happens | meaning |
|---|---|---|
3 4 + * | * finds one tree on the stack, not two | stack underflow: too few operands |
3 4 2 + | the input ends with two trees, 3 and 4+2 | too 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:
| traversal | order | prints | for (5-1)*(2+6)/4 |
|---|---|---|---|
| pre-order | node, left, right | prefix (Polish) | / * - 5 1 + 2 6 4 |
| in-order | left, node, right | infix | ( ( ( 5 - 1 ) * ( 2 + 6 ) ) / 4 ) |
| post-order | left, right, node | postfix (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).
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.