Sub topic 5
Depth-first traversal: the recursive pattern
This chapter assumes you can write recursive functions in Python, know how the call stack works, and have read the earlier chapters on the Node class and tree vocabulary. Here we cover the shared idea behind the three depth-first traversals. The next three chapters cover each order in detail.
The idea
A traversal visits every node exactly once. Depth-first traversal goes as far down one branch as it can before it backs up and tries another. It does not finish a whole level first.
A binary tree is a recursive structure. Each node is the root of a smaller tree, its subtree, and an empty child is an empty tree. That gives one recursive pattern with a base case and two recursive calls:
- If the node is
None, stop. This is the base case. - Process the left subtree.
- Process the right subtree.
- Do some work on the current node.
The only choice is where step 4 happens. Doing the work before the two recursive calls gives preorder. Doing it between them gives inorder. Doing it after both gives postorder. The left subtree is always processed before the right one.
A template
This function uses the Node class and the five-node root from the earlier chapters. It prints a message when it enters a node and again when it leaves. It marks the three places where work could go.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
root = Node(1, Node(2, Node(4), Node(5)), Node(3))
def dfs(node, depth=0):
if node is None:
return
indent = " " * depth
print(f"{indent}enter {node.value}") # preorder position
dfs(node.left, depth + 1)
print(f"{indent}between {node.value}") # inorder position
dfs(node.right, depth + 1)
print(f"{indent}leave {node.value}") # postorder position
dfs(root)Every node prints "enter" once, "between" once, and "leave" once. Preorder collects values at the "enter" lines. Inorder collects them at the "between" lines. Postorder collects them at the "leave" lines.
What the call stack does
Each call to dfs waits on the call stack while its children are processed. When the call for node 4 returns, control goes back to the call for node 2, which then moves on to node 5. The path from the root to the current node is the set of active frames on the stack. This is why the next chapters can replace recursion with an explicit stack.
Common errors
- Missing base case. Without the
Nonecheck, the code fails with anAttributeErrorwhen it reaches a missing child. - Forgetting to return results. When a traversal builds a list, each call must return its list, or the caller must pass one list down and append to it.
- Visiting at the wrong position. A single misplaced line changes the order. Check which comment marker the work sits at.
Exercise
In dfs above, which line placement gives the order 4, 5, 2, 3, 1 for the example tree, and what is that traversal called?
Show answer
Collect the value after both recursive calls, at the "leave" position. The traversal is postorder: left, right, node.