![]() |
VOOZH | about |
In this post, we'll discuss the insert() operation in a B-Tree. A new key is always inserted into a leaf node. To insert a key k, we start from the root and traverse down the tree until we reach the appropriate leaf node. Once there, the key is added to the leaf.
Unlike Binary Search Trees (BSTs), nodes in a B-Tree have a predefined range for the number of keys they can hold. Therefore, before inserting a key, we ensure the node has enough space. If the node is full, an operation called splitChild() is performed to create space by splitting the node.
To insert a new key, we go down from root to leaf. Before traversing down to a node, we first check if the node is full. If the node is full, we split it to create space. Following is the complete algorithm.
InsertionAlgorithm
1: procedure B-Tree-Insert (Node x, Key k)
2: find i such that x:keys[i] > k or i >=numkeys(x)
3: if x is a leaf then
4: Insert k into x.keys at i
5: else
6: if x:child[i] is full then
7: Split x:child[i]
8: if k > x:key[i] then
9: i = i + 1
10: end if
11: end if
12: B-Tree-Insert(x:child[i]; k)
13: end if
14: end procedure
x and a key k to insert.i in the node x where k should be inserted:x greater than k, or move to the end if no such key exists.x is a leaf node, directly insert k at position i in sorted order.x is not a leaf node, proceed to the child node at position i:x).i if k is greater than the promoted key.B-Tree-Insert procedure on the appropriate child node to continue the insertion.k is successfully inserted into a leaf node, ensuring the tree remains balanced and within its key limit.Below is the code implementation of B-Tree Insertion:
Traversal of the constructed tree is 5 6 7 10 12 17 20 30 Present Not Present
The insert operation in a B-Tree ensures efficient and balanced data storage by maintaining the structural properties of the tree. By carefully splitting nodes when they become full and promoting keys to higher levels, the tree remains balanced, with a height that grows logarithmically relative to the number of keys. This guarantees that insertion operations are fast, even for large datasets, making B-Trees an essential data structure for databases and file systems where efficient insertion and retrieval are critical.