The user wants me to build a B+ tree with range query support.
This is a programming task. I need to decide on the language (Python is usually good for this due to readability) and implement the B+ tree data structure.
Key components of a B+ tree:
Nodes (Internal vs. Leaf).
Insertion logic (splitting nodes when they overflow).
Search logic (point queries).
Range query logic (traversing the linked list of leaf nodes).
I should provide:
A class structure for the tree.
Methods for insert and range_query.
A helper function to print or visualize the tree for verification.
Example usage.
Let's draft the code structure:
Node class: keys, children (for internal) or values/next_pointer (for leaf).
Range query: Find the starting leaf, then traverse the next pointers until the end of the range.
I will write the code in Python as it's standard for algorithmic demonstrations.
Refining the implementation:
max_degree determines the number of keys. Let's stick to an orderm (max children).
Leaf nodes need a next pointer.
Internal nodes store keys and pointers to children.
Let's write the solution.
Here is a complete implementation of a B+ Tree in Python. This implementation supports insertion, point queries, and efficient range queries using the linked-list structure of the leaf nodes.
B+ Tree Implementation
python
class Node:
"""
Base class for B+ Tree nodes.
"""
def __init__(self, order):
self.order = order
self.keys = []
self.values = []
self.is_leaf = True
self.next = None # Pointer to the next leaf node (for range queries)
self.parent = None
def is_full(self):
return len(self.keys) == self.order
class BPlusTree:
def __init__(self, order=4):
self.root = Node(order)
self.order = order
def _find_leaf(self, key):
"""Traverse down the tree to find the leaf node where the key belongs."""
current = self.root
while not current.is_leaf:
# Find the first child whose key is >= search key
idx = 0
while idx < len(current.keys) and key >= current.keys[idx]:
idx += 1
current = current.values[idx] # values act as pointers to children
return current
def insert(self, key, value):
"""Insert a key-value pair into the tree."""
leaf = self._find_leaf(key)
# 1. Insert into leaf
self._insert_into_leaf(leaf, key, value)
# 2. Handle Leaf Overflow (Split)
if leaf.is_full():
self._split_leaf(leaf)
def _insert_into_leaf(self, leaf, key, value):
"""Inserts into a leaf node maintaining sorted order."""
idx = 0
while idx < len(leaf.keys) and key > leaf.keys[idx]:
idx += 1
# Handle duplicates (update value or ignore based on policy; here we update)
if idx < len(leaf.keys) and leaf.keys[idx] == key:
leaf.values[idx] = value
else:
leaf.keys.insert(idx, key)
leaf.values.insert(idx, value)
def _split_leaf(self, leaf):
"""Splits a full leaf node and pushes the middle key up."""
mid_index = (self.order) // 2
mid_key = leaf.keys[mid_index]
# Create new leaf
new_leaf = Node(self.order)
new_leaf.next = leaf.next
leaf.next = new_leaf
# Move half the keys/values to new leaf
new_leaf.keys = leaf.keys[mid_index:]
new_leaf.values = leaf.values[mid_index:]
# Truncate old leaf
leaf.keys = leaf.keys[:mid_index]
leaf.values = leaf.values[:mid_index]
# Push the mid_key up to the parent
self._insert_into_parent(leaf, mid_key, new_leaf)
def _split_internal(self, node):
"""Splits a full internal node and pushes the middle key up."""
mid_index = (self.order) // 2
mid_key = node.keys[mid_index]
# Create new internal node
new_node = Node(self.order)
new_node.is_leaf = False
# Move keys/pointers to new node (excluding mid_key which goes up)
# Keys: [1, 5, 10] split at 5 -> Left keeps [1], Right keeps [10], 5 goes up
new_node.keys = node.keys[mid_index+1:]
new_node.values = node.values[mid_index+1:]
# Update parent pointers for moved children
for child in new_node.values:
child.parent = new_node
# Truncate old node
node.keys = node.keys[:mid_index]
node.values = node.values[:mid_index+1]
self._insert_into_parent(node, mid_key, new_node)
def _insert_into_parent(self, left_node, key, right_node):
"""Inserts a key and a new pointer into the parent node."""
parent = left_node.parent
# Case 1: We are at the root (no parent)
if parent is None:
new_root = Node(self.order)
new_root.is_leaf = False
new_root.keys = [key]
new_root.values = [left_node, right_node]
self.root = new_root
left_node.parent = new_root
right_node.parent = new_root
return
# Case 2: Insert into existing parent
idx = parent.values.index(left_node)
parent.keys.insert(idx, key)
parent.values.insert(idx + 1, right_node)
right_node.parent = parent
# Check if parent needs splitting
if len(parent.keys) >= self.order: # Internal node capacity is Order-1 keys usually, but strictly > Order-1 pointers implies split
# Based on this implementation's logic, if len(keys) == order, we split
# A common B+ Tree definition: Internal node has max M children. Max keys M-1.
# If we allow len(keys) == order, we have Order+1 children essentially in this logic flow?
# Let's stick to: if keys count reaches order, split.
self._split_internal(parent)
def get(self, key):
"""Returns the value associated with a specific key."""
leaf = self._find_leaf(key)
try:
idx = leaf.keys.index(key)
return leaf.values[idx]
except ValueError:
return None
def range_query(self, start_key, end_key):
"""
Returns all key-value pairs where start_key <= key <= end_key.
Utilizes the linked-list nature of leaf nodes for O(log N + M) efficiency,
where M is the number of items in the range.
"""
results = []
# 1. Find the starting leaf node
leaf = self._find_leaf(start_key)
# 2. Iterate through leaves until we pass end_key
while leaf:
for i, key in enumerate(leaf.keys):
if key > end_key:
return results # Optimization: Stop searching immediately
if start_key <= key <= end_key:
results.append((key, leaf.values[i]))
# If the last key in this leaf is < end_key, we must check the next leaf
if leaf.keys and leaf.keys[-1] <= end_key:
leaf = leaf.next
else:
break
return results
def print_tree(self):
"""Helper to visualize the tree structure."""
print("\n--- B+ Tree Structure ---")
this_level = [self.root]
level = 0
while this_level:
print(f"Level {level}: {[n.keys for n in this_level]}")
next_level = []
for node in this_level:
if not node.is_leaf:
next_level.extend(node.values)
this_level = next_level
level += 1
print("\n--- Leaf Level (Linked List) ---")
node = self.root
while not node.is_leaf:
node = node.values[0] # Go to left-most leaf
leaves = []
while node:
leaves.append(list(zip(node.keys, node.values)))
node = node.next
print(leaves)
print("--------------------------\n")
# ==========================================
# Example Usage
# ==========================================
if __name__ == "__main__":
# Create a B+ Tree of Order 4 (Max 4 pointers per node)
# This implies max 3 keys per node (for internal nodes logic varies slightly by definition)
# Here, Order 4 implies capacity limit triggers split.
bpt = BPlusTree(order=4)
data = {
5: "Alice",
15: "Bob",
25: "Charlie",
35: "David",
45: "Eve",
10: "Frank",
20: "Grace",
30: "Henry"
}
print("Inserting data...")
for k, v in sorted(data.items()):
print(f"Insert {k}: {v}")
bpt.insert(k, v)
# bpt.print_tree() # Uncomment to see tree grow step-by-step
bpt.print_tree()
# Point Query
print(f"Get key 15: {bpt.get(15)}")
print(f"Get key 99 (Non-existent): {bpt.get(99)}")
# Range Query
print("\nRange Query [10, 35]:")
results = bpt.range_query(10, 35)
for k, v in results:
print(f" {k}: {v}")
How it Works
Structure:
Nodes: Contain keys and values.
Leaf Nodes: The values list holds the actual data. Leaf nodes are linked via the next pointer (essential for range queries).
Internal Nodes: The values list holds pointers (references) to child nodes.
Insertion:
We find the appropriate leaf.
If the leaf overflows (keys ≥ order), we split it.
The first key of the new (right) leaf is pushed up to the parent.
Splits propagate upwards if internal nodes become full.
Range Query:
We perform a standard search to find the leaf node containing the start_key.
Instead of stopping there, we iterate through the keys in that leaf.
If we reach the end of the leaf and haven't finished the range, we use the next pointer to jump to the subsequent leaf node. This avoids traversing the tree from the root for every value in the range, making it highly efficient (O(logN+).