A B-Tree is a specialized m-way tree designed to optimize data access, especially on disk-based storage systems.
- In a B-Tree of order m, each node can have up to m children and m-1 keys, allowing it to efficiently manage large datasets.
- The value of m is decided based on disk block and key sizes.
- One of the standout features of a B-Tree is its ability to store a significant number of keys within a single node, including large key values. It significantly reduces the tree’s height, hence reducing costly disk operations.
- B Trees allow faster data retrieval and updates, making them an ideal choice for systems requiring efficient and scalable data management. By maintaining a balanced structure at all times,
- B-Trees deliver consistent and efficient performance for critical operations such as search, insertion, and deletion.
Following is an example of a B-Tree of order 5 .
Properties of a B-Tree
A B Tree
of order m can be defined as an m-way
search tree which satisfies the following properties:
- All leaf nodes of a
B tree
are at the same level, i.e. they have the same depth (height of the tree). - The keys of each node of a
B tree
(in case of multiple keys), should be stored in the ascending order. - In a
B tree
, all non-leaf nodes (except root node) should have at least m/2
children. - All nodes (except root node) should have at least
m/2 - 1
keys. - If the root node is a leaf node (only node in the tree), then it will have no children and will have at least one key. If the root node is a non-leaf node, then it will have at least
2 children
and at least one key. - A non-leaf node with n-1 key values should have n non NULL children.
We can see in the above diagram that all the leaf nodes are at the same level and all non-leaf nodes have no empty sub-tree and have number of keys one less than the number of their children.
Interesting Facts about B-Tree
1. Height when the B-tree is completely full (i.e., all nodes have the maximum m
children):
h_{\text{min}} = \left\lceil \log_{m}(n + 1) \right\rceil - 1
2. Height when the B-tree is least filled (each node has the minimum t
children):
h_{\text{max}} = \left\lfloor \log_{t} \left( \frac{n + 1}{2} \right) \right\rfloor
Need of a B-Tree
The B-Tree data structure is essential for several reasons:
- Improved Performance Over M-way Trees: While M-way trees can be either balanced or skewed, B-Trees are always self-balanced. This self-balancing property ensures fewer levels in the tree, significantly reducing access time compared to M-way trees. This makes B-Trees particularly suitable for external storage systems where faster data retrieval is crucial.
- Optimized for Large Datasets: B-Trees are designed to handle millions of records efficiently. Their reduced height and balanced structure enable faster sequential access to data and simplify operations like insertion and deletion. This ensures efficient management of large datasets while maintaining an ordered structure.
Operations on B-Tree
B-Trees support various operations that make them highly efficient for managing large datasets. Below are the key operations:
Sr. No. | Operation | Time Complexity |
---|
1. | Search | O(log n) |
2. | Insert | O(log n) |
3. | Delete | O(log n) |
4. | Traverse | O(n) |
Note: "n" is the total number of elements in the B-tree
Search Operation in B-Tree
Search is similar to the search in Binary Search Tree. Let the key to be searched is k.
1.Start from the root and recursively traverse down.
2.For every visited non-leaf node
- If the current node contains k, return the node.
- Otherwise, determine the appropriate child to traverse. This is the child just before the first key greater than k.
3.If we reach a leaf node and don't find k in the leaf node, then return NULL.
Searching a B-Tree is similar to searching a binary tree. The algorithm is similar and goes with recursion. At each level, the search is optimized as if the key value is not present in the range of the parent then the key is present in another branch. As these values limit the search they are also known as limiting values or separation values. If we reach a leaf node and don’t find the desired key then it will display NULL.
Input: Search 120 in the given B-Tree.
The key 120 is located in the leaf node containing 110 and 120. The search process is complete.
Algorithm for Searching an Element in a B-Tree
C++
struct Node {
int n;
int key[MAX_KEYS];
Node* child[MAX_CHILDREN];
bool leaf;
};
Node* BtreeSearch(Node* x, int k) {
int i = 0;
while (i < x->n && k > x->key[i]) {
i++;
}
if (i < x->n && k == x->key[i]) {
return x;
}
if (x->leaf) {
return nullptr;
}
return BtreeSearch(x->child[i], k);
}
C
BtreeSearch(x, k)
i = 1
// n[x] means number of keys in x node
while i ? n[x] and k ? keyi[x]
do i = i + 1
if i n[x] and k = keyi[x]
then return (x, i)
if leaf [x]
then return NIL
else
return BtreeSearch(ci[x], k)
Java
class Node {
int n;
int[] key = new int[MAX_KEYS];
Node[] child = new Node[MAX_CHILDREN];
boolean leaf;
}
Node BtreeSearch(Node x, int k) {
int i = 0;
while (i < x.n && k > x.key[i]) {
i++;
}
if (i < x.n && k == x.key[i]) {
return x;
}
if (x.leaf) {
return null;
}
return BtreeSearch(x.child[i], k);
}
Python
class Node:
def __init__(self):
self.n = 0
self.key = [0] * MAX_KEYS
self.child = [None] * MAX_CHILDREN
self.leaf = True
def BtreeSearch(x, k):
i = 0
while i < x.n and k > x.key[i]:
i += 1
if i < x.n and k == x.key[i]:
return x
if x.leaf:
return None
return BtreeSearch(x.child[i], k)
C#
class Node {
public int n;
public int[] key = new int[MAX_KEYS];
public Node[] child = new Node[MAX_CHILDREN];
public bool leaf;
}
Node BtreeSearch(Node x, int k) {
int i = 0;
while (i < x.n && k > x.key[i]) {
i++;
}
if (i < x.n && k == x.key[i]) {
return x;
}
if (x.leaf) {
return null;
}
return BtreeSearch(x.child[i], k);
}
JavaScript
// Define a Node class with properties n, key, child, and leaf
class Node {
constructor() {
this.n = 0;
this.key = new Array(MAX_KEYS);
this.child = new Array(MAX_CHILDREN);
this.leaf = false;
}
}
// Define a function BtreeSearch that takes in a Node object x and an integer k
function BtreeSearch(x, k) {
let i = 0;
while (i < x.n && k > x.key[i]) {
i++;
}
if (i < x.n && k == x.key[i]) {
return x;
}
if (x.leaf) {
return null;
}
return BtreeSearch(x.child[i], k);
}
Applications of B-Trees
- It is used in large databases to access data stored on the disk
- Searching for data in a data set can be achieved in significantly less time using the B-Tree
- With the indexing feature, multilevel indexing can be achieved.
- Most of the servers also use the B-tree approach.
- B-Trees are used in CAD systems to organize and search geometric data.
- B-Trees are also used in other areas such as natural language processing, computer networks, and cryptography.
Advantages of B-Trees
- B-Trees have a guaranteed time complexity of O(log n) for basic operations like insertion, deletion, and searching, which makes them suitable for large data sets and real-time applications.
- B-Trees are self-balancing.
- High-concurrency and high-throughput.
- Efficient storage utilization.
Disadvantages of B-Trees
- B-Trees are based on disk-based data structures and can have a high disk usage.
- Not the best for all cases.
- For small datasets, the search time in a B-Tree might be slower compared to a binary search tree, as each node may contain multiple keys.
Related Posts
B and B+ Tree in DBMS
Intro to B Tree in DBMS
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem