Maintain Binary Search Tree Ordering
Core idea
For distinct comparable keys, a binary search tree (BST) stores smaller keys anywhere in the left subtree and larger keys in the right. Follow one branch per comparison. Insertion and lookup take O(h+1) comparisons; a skewed tree can have height n-1 (height counts edges). This example ignores duplicate inserts.
def insert(node, key): if node is None: return [key, None, None] if key < node[0]: node[1] = insert(node[1], key) elif key > node[0]: node[2] = insert(node[2], key) return noderoot = Nonefor key in [5, 2, 8, 2]: root = insert(root, key)print(root)The returned root links each new leaf to its parent.
Lookup
root = [5, [2, None, None], [8, None, None]]def contains(node, key): while node is not None: if key == node[0]: return True node = node[1] if key < node[0] else node[2] return Falseprint(contains(root, 8), contains(root, 4))A missing branch ends the search.
Common mistake
Checking only immediate children is insufficient: every descendant must obey all ancestor bounds. Sorted insertion can degenerate to a chain.
Practice
Insert 7, 3, 9, 1, 5 and trace lookup of 5 and 6.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Binary search trees
Check your understanding of binary search trees.
What is printed?
root=[7,[3,None,None],[9,None,None]]print(root[2][0])What is printed?
print(4 < 6 < 9)Worst height for n distinct increasing inserts?
Where may key 3 occur below root 5?