![]() |
VOOZH | about |
Prerequisite:Introduction of B+ trees
In this article, we will discuss that how to insert a node in B+ Tree. During insertion following properties of B+ Tree must be followed:
Here M is the order of B+ tree.
Case 1: Overflow in leaf node
Below is the illustration of inserting 8 into B+ Tree of order of 5:
Case 2: Overflow in non-leaf node
Below is the illustration of inserting 15 into B+ Tree of order of 5:
Problem: Insert the following key values 6, 16, 26, 36, 46 on a B+ tree with order = 3.
Solution:
Step 1: The order is 3 so at maximum in a node so there can be only 2 search key values. As insertion happens on a leaf node only in a B+ tree so insert search key value 6 and 16 in increasing order in the node. Below is the illustration of the same:
Step 2: We cannot insert 26 in the same node as it causes an overflow in the leaf node, We have to split the leaf node according to the rules. First part contains ceil((3-1)/2) values i.e., only 6. The second node contains the remaining values i.e., 16 and 26. Then also copy the smallest search key value from the second node to the parent node i.e., 16 to the parent node. Below is the illustration of the same:
👁 Image
Step 3: Now the next value is 36 that is to be inserted after 26 but in that node, it causes an overflow again in that leaf node. Again follow the above steps to split the node. First part contains ceil((3-1)/2) values i.e., only 16. The second node contains the remaining values i.e., 26 and 36. Then also copy the smallest search key value from the second node to the parent node i.e., 26 to the parent node. Below is the illustration of the same:
The illustration is shown in the diagram below.
Step 4: Now we have to insert 46 which is to be inserted after 36 but it causes an overflow in the leaf node. So we split the node according to the rules. The first part contains 26 and the second part contains 36 and 46 but now we also have to copy 36 to the parent node but it causes overflow as only two search key values can be accommodated in a node. Now follow the steps to deal with overflow in the non-leaf node.
First node contains ceil(3/2)-1 values i.e. '16'.
Move the smallest among remaining to the parent i.e '26' will be the new parent node.
The second node contains the remaining keys i.e '36' and the rest of the leaf nodes remain the same. Below is the illustration of the same:
Below is the python implementation of B+ tree:
['15'] ['25'] ['35'] ['45'] ['5'] Not found
Time complexity: O(log n)
Auxiliary Space: O(log n)
Below is the C++ implementation B+ tree:
The size of bucket is 3! 1 2 3 3 1 2 3 4 5
Time Complexity:
Auxiliary Space: O(n), n-> number of elements in the tree.