Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 67 / 101

Follow the branches.

Represent hierarchical data and traverse it with a deliberate order.

ADVANCED LAB
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

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.

trees.py
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)))
↳ EXPECTED OUTPUT
[1, 2, 3, 4, 6]

03 Under the hood

  1. 1

    Each recursive call handles one subtree and yields values to the caller. An absent child is the terminating base case.

  2. 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. 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

A SMALL MISSION

Write a function that counts all nodes in a binary tree.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

When does in-order traversal produce sorted values?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.