Sub topic 11
Cost of traversal: time, stack depth and tree shape
This chapter assumes you can write the recursive traversals from the earlier chapters. It also assumes you know Big-O notation and how the call stack works. Here you will work out what each traversal costs and why tree shape changes the memory bill.
Time: every node once
Every traversal visits each of the n nodes exactly once and does a constant amount of work per visit. Each node is also reached through exactly one parent link, and each empty child is checked once. That makes about 2n + 1 calls in total. Preorder, inorder, postorder and level-order are all O(n) in time, whatever the shape of the tree.
Shape affects space, not time.
Space: the stack follows the path
A depth-first traversal holds one stack frame per ancestor of the current node. That is at most h + 1 frames, where h is the height. Extra space is therefore O(h). The explicit stack in the iterative version has the same bound.
Level-order is different. The queue holds roughly one whole level at a time, so its space is O(w), where w is the maximum width of the tree.
| Shape | Height h | DFS space | Level-order space |
|---|---|---|---|
| Perfect or balanced | about log₂ n | O(log n) | O(n), the bottom level holds about n/2 nodes |
| Degenerate (a chain) | n − 1 | O(n) | O(1) |
A balanced tree is cheap for depth-first traversal and expensive for level-order. A chain is the opposite.
When the chain breaks recursion
Python limits recursion depth, by default to about 1000 frames. A degenerate tree of 5000 nodes exceeds it. The iterative version keeps its stack on the heap, so it has no such limit.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def chain(n):
root = None
for v in range(n, 0, -1):
root = Node(v, root, None) # each new node becomes the parent
return root
def height(node):
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
def inorder_iterative(root):
result, stack, current = [], [], root
while current is not None or stack:
while current is not None:
stack.append(current)
current = current.left
current = stack.pop()
result.append(current.value)
current = current.right
return result
deep = chain(5000)
try:
height(deep)
except RecursionError:
print("recursive height failed")
print(len(inorder_iterative(deep))) # 5000A hidden cost: list concatenation
The recursive preorder from earlier builds results with +. Each concatenation copies the lists. On a chain this copies about n + (n − 1) + … items, which is O(n²). To keep the O(n) bound, append to one shared list or use a generator.
Exercise
A binary tree has 1,000,000 nodes. Compare the extra space of a recursive inorder traversal and a level-order traversal when the tree is (a) perfect and (b) a single left-leaning chain.
Show answer
(a) Perfect: height is about 20, so inorder needs about 20 frames, O(log n). The bottom level holds about 500,000 nodes, so level-order needs O(n) queue space. (b) Chain: inorder needs about 1,000,000 frames, O(n), which would overflow Python's default recursion limit. Level-order holds one node at a time, so O(1).