Lesson 17 · Non-linear structures

Expression Trees

An arithmetic expression is a tree in disguise: operators branch, operands sit at the leaves, and the shape alone fixes the order of evaluation.

Expression Trees concept diagramThe expression tree for a + b × c: plus at the root, a as its left leaf, and a times node with leaves b and c on the right. Beside it, pre-order, in-order and post-order traversals give the prefix, infix and postfix forms.expression tree for a + b × c+×abcroot: applied lastleaves: operandsdeeper = evaluated first: × before +three traversals, three notationspre-order → prefix+ a × b cin-order → infixa + b × cpost-order → postfixa b c × +only infix ever needs brackets
1

Operators Branch, Operands Are Leaves

  1. Leaf – an operand: a constant or a variable.
  2. Internal node – an operator applied to its children.
  3. Subtree – a complete subexpression with its own value.
  4. Root – the operator applied last, whose value is the whole expression.

An expression tree (or binary expression tree) represents an arithmetic or logical expression as a binary tree. Every leaf is an operand, a number or a variable, and every internal node is an operator whose children are the subexpressions it combines.

The tree removes the need for parentheses and precedence rules. In a + b × c, the × node sits below the + node, so it must be evaluated first: its value is one of +'s inputs. For (a + b) × c the + node sits below ×. The text needs brackets to say that; the tree says it with shape.

For binary operators the tree is a full binary tree: every internal node has exactly two children. A unary operator such as negation has one child, which is the only exception.

  • n operands and n − 1 binary operators give 2n − 1 nodes
  • Associativity is shape too: a − b − c puts the first − deeper, on the left
2

Three Traversals, Three Notations

The three standard notations are three traversal orders of the same tree. Pre-order (node, left, right) gives prefix or Polish notation. In-order (left, node, right) gives infix. Post-order (left, right, node) gives postfix or reverse Polish notation.

Prefix and postfix are unambiguous as they stand: each operator's operands are fixed by position. Infix is not. Reading a + b × c back from the tree for (a + b) × c produces the same text as the other tree, so an in-order printer must add parentheses. The simple, always-correct rule is to wrap every internal node's output in brackets.

Traversals of the tree for (3 + 4) × (5 − 2)
TraversalVisit orderNotationResult
Pre-ordernode, left, rightprefix (Polish)× + 3 4 − 5 2
In-orderleft, node, rightinfix((3 + 4) × (5 − 2))
Post-orderleft, right, nodepostfix (reverse Polish)3 4 + 5 2 − ×
  • To convert between notations, build the tree once and traverse it in the other order
3

Building the Tree from Postfix

  1. Scan the postfix tokens from left to right.
  2. Operand – create a leaf and push it.
  3. Operator – pop the right subtree, pop the left subtree, make a new node with those children, and push it.
  4. End – exactly one tree must remain; it is the root.
  5. Reject – an operator with fewer than two items below it, or more than one tree at the end, means malformed input.

Postfix is the easiest input because every operator appears after both of its operands. By the time an operator is read, its two subtrees are already built and sitting on top of a stack.

The one detail that catches people out is order. The first pop returns the right operand and the second pop the left, because the left operand was pushed first. Swapping them silently turns 5 − 2 into 2 − 5.

Each token is pushed once and popped at most once, so construction is O(n) time and O(n) space for the stack.

  • A unary minus needs its own token (such as ~) so the builder pops one operand, not two
Key reference

Terms, operations, and practical uses

Core vocabulary

  • OperandA value or variable; always a leaf.
  • OperatorAn internal node; its children are the subexpressions it combines.
  • Polish notationPrefix: the operator comes before its operands, read by pre-order.
  • Reverse Polish notationPostfix: operands first, then the operator, read by post-order.

Costs

  • Build from postfixO(n) time, O(n) stack space.
  • EvaluateO(n) time, O(h) recursion depth.
  • Print any notationO(n): one traversal.
  • Node count2n − 1 nodes for n operands with binary operators.
Implementation

Code in Python, C++ and Java

OPS = {
    "+": lambda a, b: a + b,
    "-": lambda a, b: a - b,
    "*": lambda a, b: a * b,
    "/": lambda a, b: int(a / b),  # truncate toward zero, like C++ and Java
}


class Node:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right


def build(postfix):
    stack = []
    for token in postfix.split():
        if token in OPS:
            if len(stack) < 2:
                raise ValueError(f"operator {token} needs two operands")
            right = stack.pop()  # the top of the stack is the RIGHT operand
            left = stack.pop()
            stack.append(Node(token, left, right))
        else:
            stack.append(Node(token))
    if len(stack) != 1:
        raise ValueError(f"{len(stack)} items left on the stack, expected 1")
    return stack[0]


def evaluate(node):
    if node.left is None:
        return int(node.value)
    return OPS[node.value](evaluate(node.left), evaluate(node.right))


def prefix(node):
    if node.left is None:
        return node.value
    return f"{node.value} {prefix(node.left)} {prefix(node.right)}"


def infix(node):
    if node.left is None:
        return node.value
    return f"({infix(node.left)} {node.value} {infix(node.right)})"


def postfix(node):
    if node.left is None:
        return node.value
    return f"{postfix(node.left)} {postfix(node.right)} {node.value}"


for expression in ["3 4 + 5 2 - *", "2 3 4 * +", "3 +", "3 4"]:
    print("Postfix:", expression)
    try:
        root = build(expression)
    except ValueError as error:
        print("  error:", error)
        continue
    print("  prefix: ", prefix(root))
    print("  infix:  ", infix(root))
    print("  postfix:", postfix(root))
    print("  value:  ", evaluate(root))
#include <iostream>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

struct Node {
    std::string value;
    std::shared_ptr<Node> left, right;
    Node(std::string v, std::shared_ptr<Node> l = nullptr, std::shared_ptr<Node> r = nullptr)
        : value(std::move(v)), left(std::move(l)), right(std::move(r)) {}
};
using Tree = std::shared_ptr<Node>;

bool isOperator(const std::string& t) {
    return t == "+" || t == "-" || t == "*" || t == "/";
}

Tree build(const std::string& postfix) {
    std::vector<Tree> stack;
    std::istringstream in(postfix);
    std::string token;
    while (in >> token) {
        if (isOperator(token)) {
            if (stack.size() < 2) {
                throw std::runtime_error("operator " + token + " needs two operands");
            }
            Tree right = stack.back();  // the top of the stack is the RIGHT operand
            stack.pop_back();
            Tree left = stack.back();
            stack.pop_back();
            stack.push_back(std::make_shared<Node>(token, left, right));
        } else {
            stack.push_back(std::make_shared<Node>(token));
        }
    }
    if (stack.size() != 1) {
        throw std::runtime_error(std::to_string(stack.size()) +
                                 " items left on the stack, expected 1");
    }
    return stack.back();
}

long long evaluate(const Tree& node) {
    if (!node->left) return std::stoll(node->value);
    long long a = evaluate(node->left), b = evaluate(node->right);
    if (node->value == "+") return a + b;
    if (node->value == "-") return a - b;
    if (node->value == "*") return a * b;
    return a / b;
}

std::string prefix(const Tree& n) {
    if (!n->left) return n->value;
    return n->value + " " + prefix(n->left) + " " + prefix(n->right);
}

std::string infix(const Tree& n) {
    if (!n->left) return n->value;
    return "(" + infix(n->left) + " " + n->value + " " + infix(n->right) + ")";
}

std::string postfix(const Tree& n) {
    if (!n->left) return n->value;
    return postfix(n->left) + " " + postfix(n->right) + " " + n->value;
}

int main() {
    for (std::string expression : {"3 4 + 5 2 - *", "2 3 4 * +", "3 +", "3 4"}) {
        std::cout << "Postfix: " << expression << '\n';
        Tree root;
        try {
            root = build(expression);
        } catch (const std::runtime_error& error) {
            std::cout << "  error: " << error.what() << '\n';
            continue;
        }
        std::cout << "  prefix:  " << prefix(root) << '\n';
        std::cout << "  infix:   " << infix(root) << '\n';
        std::cout << "  postfix: " << postfix(root) << '\n';
        std::cout << "  value:   " << evaluate(root) << '\n';
    }
}
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    static class Node {
        String value;
        Node left, right;

        Node(String value, Node left, Node right) {
            this.value = value;
            this.left = left;
            this.right = right;
        }
    }

    static boolean isOperator(String t) {
        return t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/");
    }

    static Node build(String postfix) {
        Deque<Node> stack = new ArrayDeque<>();
        for (String token : postfix.trim().split("\\s+")) {
            if (isOperator(token)) {
                if (stack.size() < 2) {
                    throw new IllegalArgumentException("operator " + token + " needs two operands");
                }
                Node right = stack.pop(); // the top of the stack is the RIGHT operand
                Node left = stack.pop();
                stack.push(new Node(token, left, right));
            } else {
                stack.push(new Node(token, null, null));
            }
        }
        if (stack.size() != 1) {
            throw new IllegalArgumentException(stack.size() + " items left on the stack, expected 1");
        }
        return stack.pop();
    }

    static long evaluate(Node node) {
        if (node.left == null) return Long.parseLong(node.value);
        long a = evaluate(node.left), b = evaluate(node.right);
        switch (node.value) {
            case "+":
                return a + b;
            case "-":
                return a - b;
            case "*":
                return a * b;
            default:
                return a / b;
        }
    }

    static String prefix(Node n) {
        if (n.left == null) return n.value;
        return n.value + " " + prefix(n.left) + " " + prefix(n.right);
    }

    static String infix(Node n) {
        if (n.left == null) return n.value;
        return "(" + infix(n.left) + " " + n.value + " " + infix(n.right) + ")";
    }

    static String postfix(Node n) {
        if (n.left == null) return n.value;
        return postfix(n.left) + " " + postfix(n.right) + " " + n.value;
    }

    public static void main(String[] args) {
        for (String expression : new String[] {"3 4 + 5 2 - *", "2 3 4 * +", "3 +", "3 4"}) {
            System.out.println("Postfix: " + expression);
            Node root;
            try {
                root = build(expression);
            } catch (IllegalArgumentException error) {
                System.out.println("  error: " + error.getMessage());
                continue;
            }
            System.out.println("  prefix:  " + prefix(root));
            System.out.println("  infix:   " + infix(root));
            System.out.println("  postfix: " + postfix(root));
            System.out.println("  value:   " + evaluate(root));
        }
    }
}
Watch it run

Step through it

Running on 3 4 + 5 2 − ×

postfix34+52−×stack: bottom → top(empty)rule: operand → push a leaf; operator → pop two, push a new node
Step 1

Postfix in, tree out

The postfix form of (3 + 4) × (5 − 2) is 3 4 + 5 2 − ×. Postfix needs no parentheses and no precedence rules: every operator applies to the two values just before it. That makes a stack the only tool needed to build the tree.

Output
1 / 17
4

Evaluating the Tree

  1. Leaf – return the operand's value.
  2. Left – evaluate the left subtree.
  3. Right – evaluate the right subtree.
  4. Apply – combine the two values with the node's operator and return the result.

To evaluate a tree, evaluate both children, then apply the operator to their values. That is a post-order traversal, and it is why postfix notation evaluates so naturally: postfix is the post-order sequence.

A leaf returns its own value. An internal node's value depends only on its subtrees, so each subtree can be treated as a single number once it is computed. The traversal visits each node once, giving O(n) time and O(h) space for the recursion, where h is the tree height.

  • Watch operand order for − and ÷, and check for division by zero before applying ÷
5

Building from Infix or Prefix

From infix, precedence and brackets have to be resolved first. The usual route is to convert to postfix with the shunting-yard algorithm (see infix to postfix) and then build from postfix as above. A single-pass alternative keeps two stacks, one of operators and one of subtrees, and creates a node each time an operator is popped.

From prefix, scan the tokens from right to left with a stack. It mirrors the postfix algorithm, except that when an operator arrives the first pop is now the left operand and the second pop is the right.

  • All three routes are O(n)
6

Where Expression Trees Are Used

Any program that parses a formula once and then works with it many times keeps it as a tree.

  • Compilers and interpreters – the abstract syntax tree is this tree with extra node types for statements, calls and declarations; type checking and code generation are traversals of it
  • Calculators and spreadsheets – parse a formula once, then re-evaluate the tree whenever an input cell changes
  • Symbolic algebra – simplify or differentiate by rewriting subtrees, such as replacing x × 1 with x
  • Database query planners – store WHERE conditions as boolean trees and reorder them for speed