B+ Tree
A B+ tree is an extension of a B-tree that maintains sorted data and allows for efficient insertion, deletion, and search operations. It is commonly used in databases and file systems. The main difference between B-trees and B+ trees is that in B+ trees, all data is stored in the leaf nodes, and internal nodes only store keys to guide the search.
Key Properties of B+ Trees
Balanced Tree: All leaf nodes are at the same depth.
Node Structure: Internal nodes contain only keys and child pointers, while leaf nodes contain keys and data pointers.
Order: The maximum number of children a node can have is defined by the order
mof the B+ tree.Key Constraints:
Each internal node can have at most
m-1keys.Each internal node (except the root) must have at least
ceil(m/2) - 1keys.
Children Constraints:
Each internal node can have at most
mchildren.Each internal node (except the root) must have at least
ceil(m/2)children.
Leaf Nodes: Leaf nodes are linked together to allow for efficient range queries.
Operations
Search
To search for a key in a B+ tree:
Start at the root node.
Perform a binary search within the internal node to find the range of keys.
If the key is found in an internal node, continue to the appropriate child node.
If the key is found in a leaf node, return the data.
If the key is not found, the key does not exist.
Insertion
To insert a key into a B+ tree:
Find the appropriate leaf node where the key should be inserted.
Insert the key into the leaf node in sorted order.
If the leaf node overflows (i.e., it has
mkeys), split the node:Create a new leaf node and move the median key to the parent.
Distribute the remaining keys between the two leaf nodes.
If the parent node overflows, recursively split the parent.
Deletion
To delete a key from a B+ tree:
Find the leaf node containing the key.
Remove the key from the leaf node.
If the leaf node underflows (i.e., it has fewer than
ceil(m/2) - 1keys), rebalance the tree by borrowing a key from a sibling or merging with a sibling.If an internal node underflows, recursively rebalance the tree.
Example
Consider a B+ tree of order 3 (each node can have at most 2 keys and 3 children).
Initial Tree
Insertion of 25
Insert 25 into the appropriate leaf node.
The node [15, 20] overflows, so split it:
Move 20 to the parent.
Create a new leaf node [25].
Deletion of 10
Find 10 in the root node.
Replace 10 with its successor (15).
Delete 15 from the leaf node.
This example illustrates the basic operations of a B+ tree, including insertion and deletion, while maintaining balance and order.