Three orders, three viewpoints.
Choose when to process a node relative to its children.
01 Model the idea
Tree traversal order describes when a node is processed compared with its subtrees. Pre-order processes the node first; in-order processes it between left and right; post-order processes it last. These support different tasks: pre-order can describe construction, while post-order lets a parent use completed child results. None of these orders is automatically sorted for an arbitrary binary tree.
Every node is included exactly once in the chosen structural order.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
PRE: node, left, right
IN: left, node, right
POST: left, right, node03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
class Node:
def __init__(self, value, left=None, right=None): self.value, self.left, self.right = value, left, right
def traverse(node, order):
if node is None: return []
left, right = traverse(node.left, order), traverse(node.right, order)
if order == "pre": return [node.value] + left + right
if order == "in": return left + [node.value] + right
return left + right + [node.value]
root = Node("A", Node("B"), Node("C"))
for order in ["pre", "in", "post"]:
print(order, traverse(root, order))pre ['A', 'B', 'C'] in ['B', 'A', 'C'] post ['B', 'C', 'A']
- 1
The structural recursion is the same; only the placement of the current node changes.
- 2
This readable implementation concatenates lists at every node. On a skewed tree, repeated copying can make it quadratic. A generator or one shared append-only output list avoids that extra copying.
- 3
In-order is sorted only under a BST ordering invariant. Post-order is useful when a calculation needs both subtree answers before computing the parent answer.
04 Count the cost
O(n²) worst case for shown recursive list concatenation; O(n) with shared appends
O(n + h) peak output and recursion storage
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Implement linear-time pre-order using one shared output list.
Reveal one possible solution +
class Node:
def __init__(self, value, left=None, right=None): self.value, self.left, self.right = value, left, right
def preorder(root):
result = []
def visit(node):
if node:
result.append(node.value); visit(node.left); visit(node.right)
visit(root)
return result
print(preorder(Node("A", Node("B"), Node("C"))))06 Check your reasoning
Which order processes a parent after its children?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.