VOOZH about

URL: https://www.geeksforgeeks.org/dsa/insert-operation-in-b-tree/

⇱ Insert Operation in B-Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Insert Operation in B-Tree

Last Updated : 23 Jul, 2025

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. 

👁 Functionaility

Insertion Operation

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

  • The algorithm starts with a node x and a key k to insert.
  • Find the position i in the node x where k should be inserted:
    • Locate the first key in x greater than k, or move to the end if no such key exists.
  • If x is a leaf node, directly insert k at position i in sorted order.
  • If x is not a leaf node, proceed to the child node at position i:
    • Check if the child node is full (has the maximum number of keys allowed).
    • If the child is full:
      • Split the child node into two nodes.
      • Move the middle key of the child node up to the parent node (x).
      • Adjust the position i if k is greater than the promoted key.
  • Recursively call the B-Tree-Insert procedure on the appropriate child node to continue the insertion.
  • The process ends when k is successfully inserted into a leaf node, ensuring the tree remains balanced and within its key limit.

Example


Below is the code implementation of B-Tree Insertion:


Output
Traversal of the constructed tree is 5 6 7 10 12 17 20 30 
Present
Not Present

Conclusion

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.

Comment
Article Tags: