Java Program to Implement B+ Tree
Last Updated :
13 Jun, 2024
The B+ tree is a self-balancing tree data structure commonly used in database and file systems applications. It is an extension of B-Tree and maintains sorted data in a manner that allows us for efficient insertion, deletion and search operations. The B+Trees stores all data in a leaf node while internal nodes only store keys that act as separators.
Organization of the B+ Tree
- All leaf nodes are at the same level
- Internal nodes contain keys that direct the search to the appropriate child node
- Leaf nodes contain actual data and are linked together sequentially for easier traversal
- Each node has a defined minimum and maximum number of children or keys, ensuring balance
[20, 40]
/ | \
[10, 15] [25, 30] [45, 50]
Here, the root node has two keys (20, 40), guiding where to look. The leaves contain the actual data and are linked, allowing in-order traversal.
Implementation of B+ Tree
Implementing a B+ Tree in Java involves creating classes for nodes and the tree itself. The node class would contain references to child nodes and, in the case of leaves, links to the next leaf for traversal.
- Create a class B+Tree Node to represent a node in the tree
- Create a class B+Tree to represent the B+ Tree itself, handling insertions, deletions, and searches.
- Implement insertion logic such that when a node overflows it splits
- Implement deletion logic such that when a node underflows, it borrows from siblings or merges nodes
Basic Operations in a B+ Tree:
Operation
| Description
| Time Complexity
|
---|
Insertion
| Find the appropriate leaf node, insert the data, and manage any required splits
| O(log n)
|
---|
Deletion
| Find the node with the data, remove it, and re-balance if necessary
| O(log n)
|
---|
Search
| Traverse internal nodes based on keys until reaching the appropriate leaf node, then search within the leaf.
| O(log n)
|
---|
Java Program to Implement B+ Tree
Here is a simplified Java implementation of a B+ Tree, focusing on insertions, searches, and basic re-balancing:
Java
// Java Program to Implement B+ Tree
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// B+ Tree Node class to represent
// internal and leaf nodes
class BPlusTreeNode {
// True for leaf nodes, False for internal nodes
boolean isLeaf;
// The keys stored in this node
List<Integer> keys;
// Children nodes (for internal nodes)
List<BPlusTreeNode> children;
// Link to the next leaf node
BPlusTreeNode next;
// Constructor to initialize a node
public BPlusTreeNode(boolean isLeaf) {
this.isLeaf = isLeaf;
this.keys = new ArrayList<>();
this.children = new ArrayList<>();
this.next = null;
}
}
// B+ Tree class with basic operations: insert and search
class BPlusTree {
// Root node of the tree
private BPlusTreeNode root;
// Maximum number of keys per node
private final int order;
// Constructor to initialize the B+ Tree
public BPlusTree(int order) {
if (order < 3) {
throw new IllegalArgumentException("Order must be at least 3");
}
this.root = new BPlusTreeNode(true);
this.order = order;
}
// Find the appropriate leaf node for insertion
private BPlusTreeNode findLeaf(int key) {
BPlusTreeNode node = root;
while (!node.isLeaf) {
int i = 0;
while (i < node.keys.size() && key >= node.keys.get(i)) {
i++;
}
node = node.children.get(i);
}
return node;
}
// Insert a key into the B+ Tree
public void insert(int key) {
BPlusTreeNode leaf = findLeaf(key);
insertIntoLeaf(leaf, key);
// Split the leaf node if it exceeds the order
if (leaf.keys.size() > order - 1) {
splitLeaf(leaf);
}
}
// Insert into the leaf node
private void insertIntoLeaf(BPlusTreeNode leaf, int key) {
int pos = Collections.binarySearch(leaf.keys, key);
if (pos < 0) {
pos = -(pos + 1);
}
leaf.keys.add(pos, key);
}
// Split a leaf node and update parent nodes
private void splitLeaf(BPlusTreeNode leaf) {
int mid = (order + 1) / 2;
BPlusTreeNode newLeaf = new BPlusTreeNode(true);
// Move half the keys to the new leaf node
newLeaf.keys.addAll(leaf.keys.subList(mid, leaf.keys.size()));
leaf.keys.subList(mid, leaf.keys.size()).clear();
newLeaf.next = leaf.next;
leaf.next = newLeaf;
// If the root splits, create a new root
if (leaf == root) {
BPlusTreeNode newRoot = new BPlusTreeNode(false);
newRoot.keys.add(newLeaf.keys.get(0));
newRoot.children.add(leaf);
newRoot.children.add(newLeaf);
root = newRoot;
} else {
insertIntoParent(leaf, newLeaf, newLeaf.keys.get(0));
}
}
// Insert into the parent node after a leaf split
private void insertIntoParent(BPlusTreeNode left, BPlusTreeNode right, int key) {
BPlusTreeNode parent = findParent(root, left);
if (parent == null) {
throw new RuntimeException("Parent node not found for insertion");
}
int pos = Collections.binarySearch(parent.keys, key);
if (pos < 0) {
pos = -(pos + 1);
}
parent.keys.add(pos, key);
parent.children.add(pos + 1, right);
// Split the internal node if it exceeds the order
if (parent.keys.size() > order - 1) {
splitInternal(parent);
}
}
// Split an internal node
private void splitInternal(BPlusTreeNode internal) {
int mid = (order + 1) / 2;
BPlusTreeNode newInternal = new BPlusTreeNode(false);
// Move half the keys to the new internal node
newInternal.keys.addAll(internal.keys.subList(mid + 1, internal.keys.size()));
internal.keys.subList(mid, internal.keys.size()).clear();
// Move half the children to the new internal node
newInternal.children.addAll(internal.children.subList(mid + 1, internal.children.size()));
internal.children.subList(mid + 1, internal.children.size()).clear();
// If the root splits, create a new root
if (internal == root) {
BPlusTreeNode newRoot = new BPlusTreeNode(false);
newRoot.keys.add(internal.keys.get(mid));
newRoot.children.add(internal);
newRoot.children.add(newInternal);
root = newRoot;
} else {
insertIntoParent(internal, newInternal, internal.keys.remove(mid));
}
}
// Find the parent node of a given node
private BPlusTreeNode findParent(BPlusTreeNode current, BPlusTreeNode target) {
if (current.isLeaf || current.children.isEmpty()) {
return null;
}
for (int i = 0; i < current.children.size(); i++) {
BPlusTreeNode child = current.children.get(i);
if (child == target) {
// Parent found
return current;
}
BPlusTreeNode possibleParent = findParent(child, target);
if (possibleParent != null) {
return possibleParent;
}
}
// Parent not found
return null;
}
// Search for a key in the B+ Tree
public boolean search(int key) {
BPlusTreeNode node = findLeaf(key);
int pos = Collections.binarySearch(node.keys, key);
return pos >= 0;
}
// Display the Tree (for debugging purposes)
public void printTree() {
printNode(root, 0);
}
private void printNode(BPlusTreeNode node, int level) {
System.out.println("Level " + level + ": " + node.keys);
if (!node.isLeaf) {
for (BPlusTreeNode child : node.children) {
printNode(child, level + 1);
}
}
}
}
// Main class with example usage
public class Main {
public static void main(String[] args) {
BPlusTree tree = new BPlusTree(3);
// Insert keys into the B+ Tree
tree.insert(10);
tree.insert(20);
tree.insert(30);
tree.insert(40);
tree.insert(50);
tree.insert(60);
// Print the B+ Tree structure
System.out.println("Tree after insertion:");
tree.printTree();
// Search for keys in the B+ Tree
System.out.println("Search for 30: " + tree.search(30)); // True
System.out.println("Search for 25: " + tree.search(25)); // False
}
}
OutputTree after insertion:
Level 0: [30, 50]
Level 1: [10, 20]
Level 1: [30, 40]
Level 1: [50, 60]
Search for 30: true
Search for 25: false
Below is the explanation of the above program:
- Provides a basic structure for B+ Tree with insertion and search operations
- Handles leaf and internal splits with re-balancing logic
- Includes a print Tree method to visualize the tree structure
Applications of B+ Tree
- B+ Trees are widely used in applications that require efficient indexing and fast retrieval, including
- Database indexing for relational databases
- File system structures where efficient search, insertion, and deletion are critical
- Applications requiring ordered data with range queries, like in-memory databases or caches
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read