The user asked to build a B+ tree with range query support, which implies they want code, likely in Python, since it's commonly used. I think I shouldn’t hesitate to ask for clarification on language, but I’ll proceed with Python and provide a concise implementation with explanations. The B+ tree design needs inner nodes for keys and children, while leaves store keys, values, and pointers. I will include methods for insertion, searching, and range queries, focusing on educational clarity while ensuring it’s functional.Drafting B+ Tree Code
I need to provide a code snippet for a B+ tree, which can be complex due to the requirements for correct splits and promotions. I'll implement a generic B+ tree of order M, deciding that internal nodes can have up to M children and M-1 keys, with leaves storing L keys. I think sharing the order, such as setting L equal to M-1, might simplify things. I’ll start drafting a class for BPlusTree with necessary attributes, such as a root and methods for insertion and searching, including range queries using leaf pointers.Designing B+ Tree Algorithms
I think it's better to use inclusive intervals for our B+ tree. For searching, I’ll start at the root and traverse down until I find the leaf node. I’ll check each key in the node’s keys to decide which child to follow until I either find the target or reach the last child.
For insertion, I’ll draft a function that finds the appropriate leaf and inserts the key-value pair. If the leaf exceeds maximum keys, I’ll need to split it and possibly create a new root. I want to implement insertions recursively, so I can handle splits more effectively.Implementing B+ Tree Insertion
For the B+ tree implementation, I’ll define a private _insert function. If the node is a leaf, I’ll insert the key and value while maintaining sorted order. If the number of keys exceeds the maximum, it’ll trigger a leaf split, returning the new right node and the split key.
For internal nodes, I’ll find the correct child index, call _insert recursively, and handle any returned splits. It’s important to make sure that if the root splits, I create a new root.
I’ll also define the Node classes for both the internal and leaf nodes.Implementing Leaf and Internal Splits
For leaf nodes, I’ll split at the midpoint to maintain B+ tree properties, ensuring keys are divided correctly and promoting the first key of the new right node. The implementation will handle separating keys and values into two nodes, linking them and maintaining parent pointers.
For internal nodes, I’ll also use the midpoint to decide how to split keys and children, ensuring that children are reassigned properly. I need to enforce that after an insertion, if the number of keys exceeds the maximum, a split occurs.
I will define a range query method to gather keys and values within specified ranges while accounting for duplicates. I’ll also create a search method for key equality. Handling edge cases, especially around root splits, is essential, and I’ll code carefully to avoid disrupting the tree’s structure.Creating B+ Tree Implementation
I'm getting into the implementation details of a B+ tree. First, I’m defining a class for the tree that initializes with an order and sets the max number of keys. The _find_leaf method will help traverse the tree to locate the leaf node containing a specific key.
For the insert operation, I’ll maintain sorted keys using bisect, ensuring that duplicates can either update or append values. The recursive insert function will handle leaf and internal splits as needed, and I need to ensure that splits respect the maximum keys allowed.
The range_query method will find all key-value pairs within specified limits, managed by proper checks for empty leaves and handling edge cases. I’ll make sure to document complexity and provide a concise explanation of how B+ trees work. Finally, I’ll format everything clearly in Markdown! Below is a self‑contained B+ tree implementation in Python that supports:
Insert (key, value)
Point lookup search(key)
Range query range_query(start_key, end_key) (inclusive)
Keys are assumed to be comparable; keys are unique (duplicate inserts overwrite).
python
Example usage
python
if __name__ == "__main__":
tree = BPlusTree(order=4)
for k in [10, 20, 5, 6, 12, 30, 7, 17]:
tree.insert(k, f"val-{k}")
print(tree.search(12)) # -> "val-12"
print(tree.search(99)) # -> None
# Range query
print(tree.range_query(6, 20))
# e.g. -> [(6, 'val-6'), (7, 'val-7'), (10, 'val-10'),
# (12, 'val-12'), (17, 'val-17'), (20, 'val-20')]
If you’d like this in another language (C++, Java, Go, etc.) or with deletions / duplicate-key support, say which and I can adapt it.
from bisect import bisect_left
class Node:
def __init__(self, is_leaf=False):
self.is_leaf = is_leaf
self.keys = []
self.parent = None
class InternalNode(Node):
def __init__(self):
super().__init__(is_leaf=False)
self.children = [] # len(children) = len(keys) + 1
class LeafNode(Node):
def __init__(self):
super().__init__(is_leaf=True)
self.values = []
self.next = None # pointer to next leaf (for range scans)
class BPlusTree:
def __init__(self, order=4):
"""
order = maximum number of children in an internal node (>= 3).
So max_keys per node = order - 1.
"""
if order < 3:
raise ValueError("order must be at least 3")
self.order = order
self.max_keys = order - 1
self.root = LeafNode()
# ---- Basic search helpers ----
def _find_leaf(self, node, key):
"""Descend from 'node' to the leaf that should contain 'key'."""
while not node.is_leaf:
i = 0
while i < len(node.keys) and key >= node.keys[i]:
i += 1
node = node.children[i]
return node
def search(self, key):
"""Return value for 'key', or None if not found."""
leaf = self._find_leaf(self.root, key)
i = bisect_left(leaf.keys, key)
if i < len(leaf.keys) and leaf.keys[i] == key:
return leaf.values[i]
return None
# ---- Insertion ----
def insert(self, key, value):
"""
Insert key -> value.
If key already exists, its value is replaced.
"""
result = self._insert_recursive(self.root, key, value)
if result is not None:
# Root was split: create new root
new_child, split_key = result
new_root = InternalNode()
new_root.keys = [split_key]
new_root.children = [self.root, new_child]
self.root.parent = new_root
new_child.parent = new_root
self.root = new_root
def _insert_recursive(self, node, key, value):
"""
Insert into subtree rooted at 'node'.
Returns (new_right_node, split_key) if 'node' was split, else None.
"""
if node.is_leaf:
self._insert_into_leaf(node, key, value)
if len(node.keys) <= self.max_keys:
return None
return self._split_leaf(node)
# Internal node: find child to descend into
i = 0
while i < len(node.keys) and key >= node.keys[i]:
i += 1
child = node.children[i]
result = self._insert_recursive(child, key, value)
if result is None:
return None
new_child, split_key = result
# Insert promoted key and new_child into this internal node
node.keys.insert(i, split_key)
node.children.insert(i + 1, new_child)
new_child.parent = node
if len(node.keys) <= self.max_keys:
return None
return self._split_internal(node)
def _insert_into_leaf(self, leaf, key, value):
"""Insert key/value into a leaf (keep keys sorted, overwrite if exists)."""
i = bisect_left(leaf.keys, key)
if i < len(leaf.keys) and leaf.keys[i] == key:
# Overwrite existing
leaf.values[i] = value
else:
leaf.keys.insert(i, key)
leaf.values.insert(i, value)
# ---- Splitting nodes ----
def _split_leaf(self, leaf):
"""
Split a full leaf node.
Returns (new_right_leaf, split_key_to_promote).
"""
mid = len(leaf.keys) // 2
right = LeafNode()
right.keys = leaf.keys[mid:]
right.values = leaf.values[mid:]
leaf.keys = leaf.keys[:mid]
leaf.values = leaf.values[:mid]
# Link into leaf chain
right.next = leaf.next
leaf.next = right
right.parent = leaf.parent
split_key = right.keys[0] # first key of right node is promoted
return right, split_key
def _split_internal(self, node):
"""
Split a full internal node.
Returns (new_right_internal_node, split_key_to_promote).
"""
mid = len(node.keys) // 2
split_key = node.keys[mid]
right = InternalNode()
right.keys = node.keys[mid + 1:]
right.children = node.children[mid + 1:]
# Reassign parent pointers
for child in right.children:
child.parent = right
node.keys = node.keys[:mid]
node.children = node.children[:mid + 1]
right.parent = node.parent
return right, split_key
# ---- Range query ----
def range_query(self, start_key, end_key):
"""
Return list of (key, value) for start_key <= key <= end_key, in order.
"""
if start_key > end_key:
start_key, end_key = end_key, start_key
leaf = self._find_leaf(self.root, start_key)
i = bisect_left(leaf.keys, start_key)
result = []
while leaf is not None:
# Scan within this leaf
while i < len(leaf.keys) and leaf.keys[i] <= end_key:
result.append((leaf.keys[i], leaf.values[i]))
i += 1
# Either finished this leaf or exceeded end_key
if i < len(leaf.keys):
# Next key in this leaf is > end_key -> done
break
leaf = leaf.next
i = 0
if leaf is None or not leaf.keys or leaf.keys[0] > end_key:
break
return result