Sub topic 7
Expression Trees and Their Traversals
This chapter assumes basic recursion, object references, and the meanings of preorder, inorder, and postorder traversal.
An expression tree is a binary tree that represents an arithmetic expression. Each leaf stores an operand, such as a number or variable. Each internal node stores an operator, such as +, -, *, or /. The operator combines the values produced by its left and right subtrees.
For example, the expression (3 + 4) * 2 has this structure:
Traversal determines notation
The same tree can produce three common forms of the expression. The difference is when the operator is visited.
| Traversal | Operator position | Result for the example |
|---|---|---|
| Preorder | Before both subtrees | `* + 3 4 2` |
| Inorder | Between the subtrees | `(3 + 4) * 2` |
| Postorder | After both subtrees | `3 4 + 2 *` |
Preorder produces prefix notation, also called Polish notation. Postorder produces postfix notation, also called reverse Polish notation. Inorder produces the usual infix notation, but parentheses are needed to preserve the tree's grouping.
A traversal does not change the tree. It only changes the order in which its nodes are written.
Printing and evaluating an expression tree
The following program implements all three traversals. Its inorder function adds parentheses around every operation, so the grouping remains unambiguous.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def preorder(node, out):
if node is not None:
out.append(node.value)
preorder(node.left, out)
preorder(node.right, out)
def postorder(node, out):
if node is not None:
postorder(node.left, out)
postorder(node.right, out)
out.append(node.value)
def inorder(node):
if node.left is None and node.right is None:
return node.value
return f"({inorder(node.left)} {node.value} {inorder(node.right)})"
def evaluate(node):
if node.left is None and node.right is None:
return int(node.value)
left_value = evaluate(node.left)
right_value = evaluate(node.right)
if node.value == "+":
return left_value + right_value
if node.value == "-":
return left_value - right_value
if node.value == "*":
return left_value * right_value
if node.value == "/":
return left_value // right_value
raise ValueError("unknown operator")
root = Node(
"*",
Node("+", Node("3"), Node("4")),
Node("2"),
)
prefix = []
postfix = []
preorder(root, prefix)
postorder(root, postfix)
print("infix:", inorder(root))
print("prefix:", " ".join(prefix))
print("postfix:", " ".join(postfix))
print("value:", evaluate(root))The output is:
infix: ((3 + 4) * 2)
prefix: * + 3 4 2
postfix: 3 4 + 2 *
value: 14Evaluation naturally uses postorder. A node cannot be evaluated until the values of both children are known. This is a bottom-up computation: evaluate the left subtree, evaluate the right subtree, then apply the operator.
Common errors
- Treating an operand as an operator. Operators are internal nodes in a binary expression tree.
- Omitting parentheses from inorder output. The tree may represent a different expression without them.
- Evaluating an operator before its children. This violates the dependency represented by the tree.
- Assuming every operator has two operands. Unary operators, such as negation, need a different node shape or explicit arity.
Exercise
What postfix expression is produced by the expression tree for 8 / (2 + 2)?
Show answer
8 2 2 + /