Sub topic 6
A persistent binary search tree
This chapter assumes you know how an ordinary binary search tree (BST) works, can read Python, and know that two variables can point at the same object. The previous chapters covered structural sharing and path copying. Here you apply them to a tree.
Why a tree is a good fit
A persistent list can only share its tail. A BST is more useful because it supports ordered lookup and insertion in O(log n) time when it is balanced. If you make every node immutable, each insert returns a new tree and leaves the old one valid. Copying the whole tree would cost O(n). Path copying brings the cost down to the length of one root-to-leaf path.
The node type
A frozen dataclass makes nodes immutable. Any attempt to assign to a field raises an error, so a shared node can never change underneath another version.
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Tree:
key: int
left: Optional["Tree"] = None
right: Optional["Tree"] = NoneAn empty tree is None.
Insertion by path copying
Insertion follows the normal BST search. The difference is that each step on the way back up builds a new node instead of changing an old one.
def insert(t: Optional[Tree], key: int) -> Tree:
if t is None:
return Tree(key)
if key < t.key:
return Tree(t.key, insert(t.left, key), t.right)
if key > t.key:
return Tree(t.key, t.left, insert(t.right, key))
return tEach branch of insert does one of three things:
- When it goes left, it creates a new node with the new left child and reuses the old right child as is.
- When it goes right, it does the mirror image.
- When the key already exists, it returns the same node
t. No copy is made, so the new tree can share even the root with the old one.
Checking what is shared
Run this to see the sharing for yourself.
v1 = insert(insert(insert(None, 5), 3), 8)
v2 = insert(v1, 4)
assert v1.right is v2.right # untouched subtree is shared
assert v1.left is not v2.left # nodes on the path to the change are copied
assert v1.left.left is None # the old version is unchanged
def nodes(t):
if t is None:
return []
return [t] + nodes(t.left) + nodes(t.right)
shared = {id(n) for n in nodes(v1)} & {id(n) for n in nodes(v2)}
assert len(nodes(v1)) == 3
assert len(nodes(v2)) == 4
assert len(shared) == 1 # only the node holding 8 is commonInserting 4 walks from 5 to 3 and then to an empty slot. It copies 5 and 3 and creates a new node for 4. That is three allocations. The node holding 8 is reused.
Cost
Let h be the height of the tree. An insert allocates at most h + 1 nodes, so it takes O(h) time and O(h) extra space. For a balanced tree that is O(log n). Every other node is shared. Lookups do not allocate anything and cost the same as in a mutable BST.
Common mistakes
- Mutating a node "just this once". A mutation is visible in every version that shares the node. Keep nodes frozen.
- Copying the sibling subtree. Reuse
t.rightdirectly. A deep copy defeats sharing and turns O(log n) into O(n). - Comparing versions with
==. Dataclass equality compares contents recursively. Useisto ask whether two versions share a node.
Exercise
You start with v1 holding keys 5, 3, 8 as above, then run v3 = insert(v1, 9). Which nodes of v1 does v3 share, and how many new nodes does the insert allocate?
Show answer
The key 9 goes right of 5, then right of 8. The insert copies 5 and 8 and creates a new node for 9, which is three allocations. The only shared node is the one holding 3, which is the left subtree of the root. The new root points to the old 3 node and to the copied 8.