MCPcopy Create free account
hub / github.com/KentBeck/BPlusTree3 / BPlusTreeMap

Class BPlusTreeMap

python/bplustree/bplus_tree.py:33–637  ·  view source on GitHub ↗

B+ Tree implementation with Python dict-like API. A B+ tree is a self-balancing tree data structure that maintains sorted data and allows searches, sequential access, insertions, and deletions in O(log n). Unlike B trees, all values are stored in leaf nodes, which are linked together

Source from the content-addressed store, hash-verified

31
32
33class BPlusTreeMap:
34 """B+ Tree implementation with Python dict-like API.
35
36 A B+ tree is a self-balancing tree data structure that maintains sorted data
37 and allows searches, sequential access, insertions, and deletions in O(log n).
38 Unlike B trees, all values are stored in leaf nodes, which are linked together
39 for efficient range queries.
40
41 Attributes:
42 capacity: Maximum number of keys per node.
43 root: The root node of the tree.
44 leaves: The leftmost leaf node (head of linked list).
45
46 Example:
47 >>> tree = BPlusTreeMap(capacity=32)
48 >>> tree[1] = "one"
49 >>> tree[2] = "two"
50 >>> print(tree[1])
51 one
52 >>> for key, value in tree.items():
53 ... print(f"{key}: {value}")
54 1: one
55 2: two
56 """
57
58 def __init__(self, capacity: int = DEFAULT_CAPACITY) -> None:
59 """Create a B+ tree with specified node capacity.
60
61 Args:
62 capacity: Maximum number of keys per node (minimum 4).
63
64 Raises:
65 InvalidCapacityError: If capacity is less than 4.
66 """
67 if capacity < MIN_CAPACITY:
68 raise InvalidCapacityError(
69 f"Capacity must be at least {MIN_CAPACITY} to maintain B+ tree invariants"
70 )
71 self.capacity = capacity
72 self._rightmost_leaf_cache: Optional[LeafNode] = None
73
74 original = LeafNode(self.capacity)
75 self.leaves: LeafNode = original
76 self.root: Node = original
77
78 @classmethod
79 def from_sorted_items(
80 cls, items, capacity: int = DEFAULT_CAPACITY
81 ) -> "BPlusTreeMap":
82 """Bulk load from sorted key-value pairs for 3-5x faster construction.
83
84 Args:
85 items: Iterable of (key, value) pairs that MUST be sorted by key.
86 capacity: Node capacity (minimum 4).
87
88 Returns:
89 BPlusTreeMap instance with loaded data.
90

Calls

no outgoing calls