B+ Tree
Overview
A B+ tree is a self-balancing tree data structure that maintains sorted data and allows for efficient insertion, deletion, and search operations. Unlike regular B-trees, B+ trees store all data in leaf nodes, with internal nodes only storing keys for navigation.
Properties
- All leaves are at the same level
- Nodes are at least half full
- Data is stored only in leaf nodes
- Leaf nodes are linked for efficient range queries
- Height remains balanced automatically
Insertion Process
Watch how elements are inserted into a B+ tree:
Insertion Steps
- Find the appropriate leaf node
- If leaf has space, insert the key
- If leaf is full:
- Split the node
- Create new internal node if needed
- Redistribute keys
- Update parent nodes as needed
Deletion Process
Watch how elements are deleted from a B+ tree:
Deletion Steps
- Find the leaf node containing the key
- Remove the key
- If node becomes underfull:
- Try borrowing from siblings
- Merge with sibling if borrowing not possible
- Update parent nodes and possibly reduce tree height
Time Complexity
Operation | Average Case | Worst Case |
---|---|---|
Search | O(log n) | O(log n) |
Insert | O(log n) | O(log n) |
Delete | O(log n) | O(log n) |
Space Complexity
- O(n) where n is the number of keys
Use Cases
- Database indexing
- File systems
- Multilevel indexing
- Range queries
- Sequential access optimization
Advantages
- Balanced height ensures consistent performance
- Efficient range queries via leaf node links
- High fanout reduces tree height
- Good for disk-based storage systems
Disadvantages
- Complex implementation
- Extra space overhead
- Rebalancing operations can be costly
Implementation Example
class BPlusTreeNode {
boolean isLeaf;
List<Integer> keys;
List<BPlusTreeNode> children;
BPlusTreeNode next; // For leaf node linking
public BPlusTreeNode(boolean leaf) {
this.isLeaf = leaf;
this.keys = new ArrayList<>();
this.children = new ArrayList<>();
this.next = null;
}
}
class BPlusTree {
private BPlusTreeNode root;
private int t; // Minimum degree
public BPlusTree(int t) {
this.root = new BPlusTreeNode(true);
this.t = t;
}
public void insert(int key) {
// Implementation details...
}
public void delete(int key) {
// Implementation details...
}
}