Follow the branches.
Represent hierarchical data and traverse it with a deliberate order.
01 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.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
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]
03 Under the hood
- 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 Your turn, builder
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))))05 Check your signal
When does in-order traversal produce sorted values?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.