COMPUTER ENGINEER

← BlogDATA STRUCTURES / ALGORITHMSPython example pack ↓

Trees and indexes · 18 / 53

Binary trees, BSTs and order statistics

Understand → trace → implement → justify

1 min reading · allow extra time for practice

A binary tree permits at most two children; a BST adds ordering. Decide how duplicates are represented. Checking only immediate children does not validate a BST: descendants must respect ancestor bounds.

Search follows one root-to-node path and costs O(h). Sorted insertion can form a chain with h=n. Inorder traversal produces sorted keys. Deleting a node handles leaf, one-child and two-child cases; the latter can use a successor/predecessor and remove its original node.

Subtree-size augmentation supports rank and select. Rotations and edits must update metadata, not merely links. Without balancing, order-statistic operations can still become linear.

A worked trace

Root10, left5, right child12 under5: local5<12 holds, but12 violates the ancestor bound in10’s left subtree.

Cost and assumptions

Search/insert/delete O(h): balanced O(log n), chain O(n). Traversal Θ(n), stack O(h).

Executable example

Run with Python 3. Assertions check a small example; they do not constitute a general correctness proof. Some advanced examples are explicitly small models or reference oracles, not full production implementations.

Python 3
def valid_bst(node, lo=float("-inf"), hi=float("inf")):
    if node is None: return True
    key, left, right = node
    return (lo < key < hi and valid_bst(left, lo, key)
            and valid_bst(right, key, hi))
assert not valid_bst((10,(5,None,(12,None,None)),None))

TEST YOUR UNDERSTANDING

Your turn

Is this validator sufficient if duplicate keys are allowed?

Reveal the reasoning

No; it enforces a strict BST contract. Choose counts or a consistent duplicate-side policy and update all operations accordingly.

Take it further

  1. Write down the input contract and the invariant before changing the example.
  2. Add empty, boundary, duplicate and adversarial cases where they are relevant. Compare with a simple oracle.
  3. Derive the cost under the stated model; measure several input sizes and explain discrepancies.

Primary reading & lecture notes

Original explanations in this course; these references provide proofs and further reading. Source links may cover the broader module.

MIT 6.006 · Introduction to Algorithms ↗Pat Morin · Open Data Structures ↗
Solve the exercise before moving on.