Follow the branches.
Represent hierarchical data and traverse it with a deliberate order.
01 Model the idea
A tree represents a hierarchy of nodes connected by parent-child relationships. A binary tree gives each node up to two children. A binary search tree adds an ordering invariant, but a general binary tree does not. An in-order traversal visits left subtree, node, then right subtree; its output is sorted only when the search-tree ordering invariant holds.
The traversal order is defined independently from any search-tree ordering.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
VISIT left subtree
YIELD current node
VISIT right subtree03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
from dataclasses import dataclass
@dataclass
class Node:
value: int
left: "Node | None" = None
right: "Node | None" = None
def inorder(node):
if node is not None:
yield from inorder(node.left)
yield node.value
yield from inorder(node.right)
root = Node(4, Node(2, Node(1), Node(3)), Node(6))
print(list(inorder(root)))[1, 2, 3, 4, 6]
- 1
Each recursive call handles one subtree and yields values to the caller. An absent child is the terminating base case.
- 2
This fixture also satisfies binary-search-tree ordering, which is why its in-order output is sorted. Do not assume that for every binary tree.
- 3
Traversing every node takes linear time. Recursion uses space proportional to tree height; an unbalanced chain can reach Python’s recursion limit. Balanced search trees are needed for reliable logarithmic search depth.
04 Count the cost
O(n) traversal
O(h) traversal stack; O(n) if collecting output
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
Write a function that counts all nodes in a binary tree.
Reveal one possible solution +
from dataclasses import dataclass
@dataclass
class Node:
value: int
left: "Node | None" = None
right: "Node | None" = None
def count(node):
return 0 if node is None else 1 + count(node.left) + count(node.right)
print(count(Node(2, Node(1), Node(3))))06 Check your reasoning
When does in-order traversal produce sorted values?
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.