Sub topic 8
Postorder: left, right, node
This chapter covers postorder traversal. It assumes you know recursion and the call stack, can read the Node class from earlier chapters, and understand basic Big-O notation. The examples reuse the five-node tree built earlier.
The pattern
Postorder visits both subtrees first and visits the current node last. The order is left, right, node. A node is never visited until every node below it has been visited.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# 1
# / \
# 2 3
# / \
# 4 5
root = Node(1, Node(2, Node(4), Node(5)), Node(3))
def postorder(node):
if node is None:
return []
return postorder(node.left) + postorder(node.right) + [node.value]
print(postorder(root)) # [4, 5, 2, 3, 1]The base case returns an empty list for None. Each call collects the left result, then the right result, then appends its own value.
Tracing the order
Start at node 1. The call descends left to node 2, then left again to node 4. Node 4 has no children, so it is visited first. Back in node 2, the right child 5 is visited, and then 2 itself. Only now does the traversal return to node 1 and go right to node 3. Node 3 is visited, and the root 1 comes last.
The root is always last, and every leaf appears before its parent.
When postorder is the right choice
Use postorder when a node's answer depends on its children's answers. Children are finished before the parent is processed, so the parent can combine their results.
- Computing height or size. A node's height is one more than its taller child's height, and its size is one plus the sizes of its children.
- Deleting a tree. In languages with manual memory management, you must free the children before the parent, or you lose the pointers to them.
- Evaluating expression trees. The operands (children) must be evaluated before the operator (parent). Postorder on an expression tree gives postfix notation.
The height function from earlier chapters is already a postorder computation. It handles both children, then uses their results:
def height(node):
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
print(height(root)) # 2Common errors
- Swapping the order of the three terms. Moving
[node.value]to the middle gives inorder. Moving it to the front gives preorder. Only the position of the node changes between the three traversals. - Forgetting the base case. Without the
Nonecheck, the function fails with anAttributeErrorwhen it reaches a leaf's missing child. - Expecting postorder to be reversed preorder. It is not, in general. Reversing preorder gives node, right, left reversed, which is left, right, node only when you swap the child order in the preorder. This trick is useful for iterative postorder, but it is a different traversal.
- Building lists by concatenation on large trees. The
+operator copies lists at each call, which can cost more than O(n) overall on deep trees. An accumulator list passed down, withappend, avoids this.
Exercise
Write a function size(node) that returns the number of nodes in a binary tree using the postorder pattern. What does it return for root?
Show answer
def size(node):
if node is None:
return 0
return size(node.left) + size(node.right) + 1
It returns 5 for root. The function combines the results from both subtrees first, then adds one for the current node.
Exercise
What is the postorder sequence of a tree whose root is 10, with left child 5 and right child 15, where 5 has no children and 15 has a left child 12?
Show answer
[5, 12, 15, 10]. The left subtree gives 5. The right subtree visits 12, then 15. The root 10 comes last.