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

Search down the branches.

Maintain a search-tree invariant and account for a tree’s actual height.

ADVANCED LAB
BY NAVAN SAMI◷ 12 MIN READPYTHON 3

01 The idea

A binary search tree places smaller keys in the left subtree and larger keys in the right subtree under a chosen duplicate policy. Search compares with a node and chooses one branch. Its cost is proportional to height, not automatically logarithmic: a chain-shaped tree behaves like a linear scan. This example ignores duplicate insertions, treating the tree as a set.

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.

binary_search_trees.py
from dataclasses import dataclass
@dataclass
class Node:
    value: int
    left: "Node | None" = None
    right: "Node | None" = None
def insert(node, value):
    if node is None: return Node(value)
    if value < node.value: node.left = insert(node.left, value)
    elif value > node.value: node.right = insert(node.right, value)
    return node
def contains(node, value):
    while node is not None:
        if value == node.value: return True
        node = node.left if value < node.value else node.right
    return False
root = None
for value in [4, 2, 6, 1, 3]: root = insert(root, value)
print(contains(root, 3), contains(root, 9))
↳ EXPECTED OUTPUT
True False

03 Under the hood

  1. 1

    insert returns the subtree root so callers can reconnect it, including the very first insertion into None.

  2. 2

    The strict comparisons make the duplicate policy explicit. A record index might instead update a value or store a collection for duplicate keys.

  3. 3

    Balanced search trees keep height logarithmic through extra invariants and rebalancing. For ordinary Python application key lookup, a dictionary is usually simpler unless ordered operations are specifically needed.

04 Your turn, builder

A SMALL MISSION

Test repeated inserts and confirm searching for an absent key remains false.

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 insert(node, value):
    if node is None: return Node(value)
    if value < node.value: node.left = insert(node.left, value)
    elif value > node.value: node.right = insert(node.right, value)
    return node
def contains(node, value):
    while node is not None:
        if value == node.value: return True
        node = node.left if value < node.value else node.right
    return False
root = None
for value in [4, 2, 6, 2]: root = insert(root, value)
assert contains(root, 2) is True
assert contains(root, 9) is False
assert root.left.value == 2 and root.left.left is None and root.left.right is None
print("Duplicate and absent-key checks passed")

05 Check your signal

QUICK SIGNAL CHECK

What determines search cost in an unbalanced BST?

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.