Examining the Core Objective
I've been focusing on the user's need for a B+ Tree implementation. I'm prioritizing the inclusion of range query functionality, which seems to be a central requirement. Currently, I'm mentally parsing the initial prompt, aiming to outline the basic design parameters.
Deconstructing the Requirements
I'm now fully immersed in the design, breaking down the essential classes. I'm focusing on the Node and BPlusTree classes, ensuring that the fundamental components align with B+ Tree principles. My current line of thought is concentrated on incorporating the 'linked leaves' for efficient range queries.
Formulating the Class Structure
I'm now deeply engrossed in finalizing the class structures. My thoughts center on the Node class attributes, focusing on the children, keys, is_leaf flags and the all-important 'next' pointer for facilitating the range query functionality. It appears the method implementations will be relatively straightforward after I concretize these classes.
Defining Insertion & Search Methods
My train of thought now focuses on the core implementation details of insertion and searching within the tree. I'm carefully considering edge cases and boundary conditions for insertion, particularly splitting nodes and updating parent nodes. I'm planning to implement the search functions, which are critical for the range query, as helper functions.
Defining Search & Helper Methods
I'm now moving on to the more practical aspects, implementing the search functionality and auxiliary helper methods to make range queries easier. This now includes defining a private _find method and a _find_leaf method. I'm focusing on efficiency and code clarity as I refine the implementation details to support range lookups.
Implementing B+ Tree Structure
The next step is now focusing on the split logic for both leaf and internal nodes, the core functionality for insertion and balancing. I'm now refining the Python code, concentrating on the edge cases of these splits, while making sure the keys and pointers are managed correctly throughout the entire process, especially during propagation. Also, my focus will be on the proper use of linked leaves for range queries, and ensuring all nodes and their keys are in sorted order.
Here is a complete, commented Python implementation of a B+ Tree.
Key Features of this Implementation:
- Singly Linked Leaves: The leaf nodes are connected via a
next pointer, allowing for O(N) complexity when strictly iterating through a range (once the start is found).
- Order (m): You can define the order of the tree.
- Internal vs. Leaf Split: Handles the specific logic where leaf splits copy the key up (retaining it in the leaf), while internal node splits push the key up (removing it from the internal node).
Python Code
import math
class Node:
def __init__(self, order):
self.order = order
self.keys = []
self.values = []
self.leaf = True
self.children = []
self.parent = None
self.next = None # Pointer to the next leaf node
def add(self, key, value=None):
"""Adds a key-value pair to string node."""
if not self.keys:
self.keys.append(key)
self.values.append(value)
return
for i, item in enumerate(self.keys):
if key == item:
self.values[i] = value # Update existing
return
elif key < item:
self.keys.insert(i, key)
self.values.insert(i, value)
return
self.keys.append(key)
self.values.append(value)
def split(self):
"""Splits the node into two and returns the (key, right_node)."""
left = self
right = Node(self.order)
mid = self.order // 2
# differentiating between leaf split and internal split
if self.leaf:
# B+ Tree Leaf Split:
# Split happens at mid. Middle key stays in right half.
# Copy of middle key goes up to parent.
right.keys = left.keys[mid:]
right.values = left.values[mid:]
left.keys = left.keys[:mid]
left.values = left.values[:mid]
# Link the leaves
right.next = left.next
left.next = right
# For leaf split, the key to push up is the first key of the new right node
return right.keys[0], right
else:
# B+ Tree Internal Split:
# Middle key moves UP to parent (does not stay in child).
right.leaf = False
right.children = left.children[mid + 1:]
right.keys = left.keys[mid + 1:]
split_key = left.keys[mid]
left.keys = left.keys[:mid]
left.children = left.children[:mid + 1]
# Update parent pointers for the children moved to the new right node
for child in right.children:
child.parent = right
return split_key, right
class BPlusTree:
def __init__(self, order=3):
self.root = Node(order)
self.order = order
def _find(self, node, key):
"""Helper to find the correct leaf node for a key."""
if node.leaf:
return node
for i, item in enumerate(node.keys):
if key < item:
return self._find(node.children[i], key)
# If key is larger than all keys, go to the last child
return self._find(node.children[-1], key)
def insert(self, key, value=None):
"""Inserts a key (and optional value) into the tree."""
if value is None: value = key # Treat key as value if no value provided
leaf = self._find(self.root, key)
leaf.add(key, value)
if len(leaf.keys) >= self.order:
self._split_node(leaf)
def _split_node(self, node):
key, right = node.split()
if node.parent is None:
# Create a new root if the current root split
new_root = Node(self.order)
new_root.leaf = False
new_root.keys.append(key)
new_root.children.append(node)
new_root.children.append(right)
node.parent = new_root
right.parent = new_root
self.root = new_root
else:
parent = node.parent
# Insert key and child into parent
# Find position
index = 0
for i, item in enumerate(parent.keys):
if key < item:
index = i
break
index = i + 1
parent.keys.insert(index, key)
parent.children.insert(index + 1, right)
right.parent = parent
# Recursively split parent if needed
if len(parent.keys) >= self.order:
self._split_node(parent)
# ==========================================
# RANGE QUERY IMPLEMENTATION
# ==========================================
def range_query(self, start, end):
"""Returns a list of values between start and end (inclusive)."""
result = []
# 1. Find the leaf node containing the start key
node = self._find(self.root, start)
# 2. Traverse the linked list of leaves
while node:
for i, key in enumerate(node.keys):
if key >= start:
if key > end:
# We have exceeded the range, stop.
return result
result.append(node.values[i])
# Move to the next leaf node
node = node.next
return result
def print_tree(self, node=None, level=0):
if node is None:
node = self.root
print("Minimum: " + str(level) + " " + str(node.keys))
if not node.leaf:
for child in node.children:
self.print_tree(child, level + 1)
# ==========================================
# DEMONSTRATION
# ==========================================
# Create a B+ Tree of order 4 (Max 3 keys per node)
bpt = BPlusTree(order=4)
# Insert distinct data points
data = [10, 20, 5, 6, 12, 30, 7, 17]
print(f"Inserting: {data}")
for item in data:
bpt.insert(item)
print("\n--- Tree Structure (Level Order approximate) ---")
bpt.print_tree()
# Perform Range Queries
print("\n--- Range Query Tests ---")
q1_start, q1_end = 5, 10
print(f"Query [{q1_start}, {q1_end}]: {bpt.range_query(q1_start, q1_end)}")
q2_start, q2_end = 12, 30
print(f"Query [{q2_start}, {q2_end}]: {bpt.range_query(q2_start, q2_end)}")
q3_start, q3_end = 6, 18
print(f"Query [{q3_start}, {q3_end}]: {bpt.range_query(q3_start, q3_end)}")
How the Range Query Works
The efficiency of a B+ Tree range query comes from the fact that we don't need to traverse the tree back up to the root or parents once we find the start point.
- Search for Start (O(logN)):
The
_find method performs a standard tree search to locate the leaf node containing the start key.
- Scan Linked Leaves (O(K)):
Once at the leaf, we iterate through the keys.
- If
key < start: Ignore.
- If
start <= key <= end: Add to results.
- If
key > end: Stop immediately.
- Traverse Neighbors:
If we reach the end of a leaf node and haven't hit the
end key yet, we use node.next to jump directly to the sibling leaf node on the right.
B+ Tree vs. Standard B-Tree for Range support
- B-Tree: You must perform an in-order traversal (recursively going up and down pointers) to find the next key, which is computationally expensive and results in random memory/disk access.
- B+ Tree: Since all data is in the leaves and the leaves are linked sequentially, fetching the next block of data is extremely fast (often the next memory block or subsequent disk sector).