Sub topic 7
Expression trees and their traversals
This chapter assumes you know the four standard traversals (preorder, inorder, postorder, level order), recursion, and the idea of a stack. An expression tree is a binary tree that stores an arithmetic expression. Preorder, inorder and postorder traversals of it give the prefix, infix and postfix forms of the expression. GATE asks about this link often.
What an expression tree is
In an expression tree:
- Each leaf holds an operand, such as a variable or a number.
- Each internal node holds an operator.
- The children of an operator node are its operands. A binary operator has exactly two children, and its left child is the left operand.
- The value of a node is its operator applied to the values of its two subtrees.
The expression (a + b) * (c - d) gives this tree:
The tree has no parentheses. The shape of the tree already says that a + b is computed before the multiplication. Parentheses, operator precedence and associativity rules are only needed when the expression is written as a flat string. Once it is a tree, the structure carries that information.
Traversals give the three notations
Each traversal of the tree above produces a different string:
| Traversal | Order of visiting | Notation | Result for the tree above |
|---|---|---|---|
| Preorder | node, left, right | Prefix (Polish) | `* + a b - c d` |
| Inorder | left, node, right | Infix | `a + b * c - d` (parentheses lost) |
| Postorder | left, right, node | Postfix (reverse Polish) | `a b + c d - *` |
The inorder result has a problem. Printed with no extra symbols, a + b * c - d could mean the tree above or many other trees. To get the correct infix form you must print ( before the left subtree and ) after the right subtree for every internal node. Prefix and postfix need no parentheses. If every operator is binary, each string corresponds to exactly one tree.
Level-order traversal of an expression tree has no standard notation and is rarely asked about in this context.
A second worked example
Take a + b * c - d. Standard precedence says * binds tighter than + and -. Addition and subtraction have equal precedence and associate left to right. So the expression means ((a + (b * c)) - d).
- The root is the last operation performed, which is the final
-. - Its left subtree is
a + (b * c), with+as its root. - Its right subtree is the single leaf
d. - Inside the
+subtree, the right child is the*node with leavesbandc.
The traversals are:
- Preorder (prefix):
- + a * b c d - Postorder (postfix):
a b c * + d - - Inorder without parentheses:
a + b * c - d
A useful rule: the root of an expression tree is the operator applied last. In postfix the last symbol is that operator. In prefix the first symbol is that operator.
Building a tree from postfix
You read postfix left to right with a stack:
- If the token is an operand, push a new leaf node.
- If the token is an operator, pop two nodes. The first pop is the right operand and the second pop is the left operand. Make a new node for the operator with those as children, and push it.
- After the last token, the stack holds one node, which is the root.
The order of the two pops is a common source of errors. For a b -, the stack holds a below b. Popping gives b first, so b must be the right child. Swapping them turns a - b into b - a.
import operator
class Node:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
OPS = {"+": operator.add, "-": operator.sub,
"*": operator.mul, "/": operator.truediv}
def build_from_postfix(tokens):
stack = []
for t in tokens:
if t in OPS:
right = stack.pop()
left = stack.pop()
stack.append(Node(t, left, right))
else:
stack.append(Node(t))
return stack.pop()
def prefix(node):
if node is None:
return []
return [node.key] + prefix(node.left) + prefix(node.right)
def postfix(node):
if node is None:
return []
return postfix(node.left) + postfix(node.right) + [node.key]
def infix(node):
if node.left is None and node.right is None:
return str(node.key)
return "(" + infix(node.left) + " " + node.key + " " + infix(node.right) + ")"
def evaluate(node, env):
if node.left is None and node.right is None:
return env[node.key]
a = evaluate(node.left, env)
b = evaluate(node.right, env)
return OPS[node.key](a, b)
root = build_from_postfix("a b c * + d -".split())
print(" ".join(prefix(root)))
print(" ".join(postfix(root)))
print(infix(root))
print(evaluate(root, {"a": 2, "b": 3, "c": 4, "d": 5}))The program prints:
- + a * b c d
a b c * + d -
((a + (b * c)) - d)
9The value is 2 + 3 × 4 − 5 = 9. Note that evaluate is a postorder traversal. It computes both subtrees first and then applies the operator at the node. This is why postfix is easy to evaluate with a stack, as the next section shows.
Evaluating postfix without building a tree
Postfix evaluation is the same stack procedure, except that you store values instead of nodes. For 5 3 2 * + 4 -:
| Token | Action | Stack (bottom to top) |
|---|---|---|
| 5 | push | 5 |
| 3 | push | 5, 3 |
| 2 | push | 5, 3, 2 |
| * | pop 2 and 3, push 3 × 2 | 5, 6 |
| + | pop 6 and 5, push 5 + 6 | 11 |
| 4 | push | 11, 4 |
| - | pop 4 and 11, push 11 − 4 | 7 |
The result is 7. The maximum stack depth during evaluation depends on the shape of the tree. A GATE question may ask for the maximum number of items on the stack. Simulate it as in the table and read off the largest stack height.
Building a tree from prefix
You can scan prefix tokens from right to left and use the same stack method. The only change is the pop order. With a right-to-left scan, the first pop is the left operand and the second pop is the right operand. Alternatively, reverse the prefix string and treat it like postfix, then swap the roles of the children.
Counting properties
Expression trees with only binary operators are full binary trees. Every internal node has exactly two children. This gives some counting facts from the earlier chapter on tree properties:
- If there are
noperands (leaves), there aren - 1operators (internal nodes). - The total number of nodes is
2n - 1. - A postfix expression with
noperands andn - 1binary operators has2n - 1tokens.
Unary operators such as negation break these formulas. A unary operator node has one child. A tree with unary operators is no longer full, and a bare traversal string may not determine the tree. In that case the string needs the arity (number of operands) of each operator to be reconstructed.
Common mistakes
- Swapping the left and right operands for
-and/. Addition and multiplication hide this error because they are commutative. Subtraction and division do not. - Trusting inorder without parentheses. It loses the grouping. Two different trees can give the same bare inorder string.
- Ignoring associativity.
a - b - cmeans(a - b) - c, so the tree has-at the root with a-subtree on the left. An exponent operator^normally associates right to left, soa ^ b ^ chas^at the root with the^subtree on the right. - Reading prefix left to right with the postfix rule. The pop order differs for the two forms, as explained above.
Summary of the working model
- An expression tree puts operands at the leaves and operators at internal nodes.
- Preorder, inorder and postorder give prefix, infix and postfix forms.
- Only the fully parenthesized inorder is unambiguous.
- Postorder is the order of evaluation. A stack evaluates postfix in one left-to-right pass.
- With
noperands and binary operators, the tree has2n - 1nodes.
Exercise
A binary expression tree has the preorder sequence + * a b - c d. Write its postorder sequence and its fully parenthesized infix form.
Show answer
The root is +. Its left subtree is * a b and its right subtree is - c d. Postorder is a b * c d - +. The infix form is ((a * b) + (c - d)).
Exercise
Evaluate the postfix expression 6 2 3 + - 3 8 2 / + * 2 ^ 3 +, where ^ is exponentiation. Hint: apply the pop rule carefully, because the first pop is the right operand.
Show answer
Work through the stack. 6 2 3 + gives 6, 5. Then - gives 6 − 5 = 1. Next 3 8 2 / gives 1, 3, 4 (since 8 / 2 = 4). Then + gives 1, 7. Then * gives 7. Then 2 ^ gives 49. Finally 3 + gives 52. The result is 52.
Exercise
An expression uses only binary operators and has 9 operators. How many operands does it have, how many nodes does its tree have, and how many tokens does its postfix form contain?
Show answer
With binary operators, operands = operators + 1 = 10. The tree has 10 + 9 = 19 nodes, and the postfix form has 19 tokens.