Sub topic 15
Applications: expression trees and serialization
This chapter assumes you can write the recursive preorder, inorder and postorder traversals from earlier chapters, and that you know the Node class (value, left, right). Here two traversals do real work: postorder evaluates an expression, and preorder saves a tree as text.
Expression trees
An expression tree stores arithmetic in the shape of the tree. Leaves hold numbers. Internal nodes hold operators, and each operator's two children are its operands. The expression (2 + 3) * 4 becomes this tree:
The tree needs no parentheses, because grouping is carried by the structure. To evaluate it, you must know both operand values before applying the operator. That is a postorder traversal: left, right, then the node.
import operator
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
OPS = {"+": operator.add, "-": operator.sub,
"*": operator.mul, "/": operator.truediv}
def evaluate(node):
if node.left is None and node.right is None:
return node.value
left_value = evaluate(node.left)
right_value = evaluate(node.right)
return OPS[node.value](left_value, right_value)
expr = Node("*", Node("+", Node(2), Node(3)), Node(4))
print(evaluate(expr)) # 20Each traversal of this tree produces a different notation:
| Traversal | Output for the tree above | Notation |
|---|---|---|
| Preorder | `* + 2 3 4` | Prefix |
| Inorder | `2 + 3 * 4` | Infix, with parentheses lost |
| Postorder | `2 3 + 4 *` | Postfix |
Serialization
Serialization turns a tree into a string or bytes so you can store or send it. Deserialization rebuilds the tree. A preorder list of values is not enough on its own, because many different tree shapes give the same list. The fix is to write a marker, here #, for every missing child. The root comes first, so the reader always knows what it is reading.
def serialize(node):
if node is None:
return "#"
return f"{node.value},{serialize(node.left)},{serialize(node.right)}"
def deserialize(text):
tokens = iter(text.split(","))
def build():
token = next(tokens)
if token == "#":
return None
node = Node(int(token))
node.left = build()
node.right = build()
return node
return build()
root = Node(1, Node(2, Node(4), Node(5)), Node(3))
text = serialize(root)
print(text) # 1,2,4,#,#,5,#,#,3,#,#
print(serialize(deserialize(text)) == text) # Truedeserialize consumes tokens in the same order serialize produced them. The shared iterator is what lets the left call finish before the right call starts.
Common errors
- Leaving out the
#markers. The string is then ambiguous, and you cannot rebuild the tree. - Calling
build()for the right child before the left. The order must match the order used when writing. - Splitting on a comma when values may contain commas. Choose a separator that cannot appear in your data.
- Recursing on very deep trees. A degenerate tree with thousands of nodes can exceed Python's recursion limit, so use an explicit stack instead.
Both functions visit each node once, so they run in O(n) time. The recursion depth is the tree height.
Exercise
A tree is serialized in preorder with # for missing children as "7,3,#,#,9,#,#". Draw it in words: what are the root, its left child and its right child, and does either child have children?
Show answer
The root is 7. Its left child is 3 and its right child is 9. Reading the string, 3 is followed by two # markers, so it has no children. The same is true of 9. The tree has three nodes.