Python Data Structure and Algorithm Tutorial – Insertion on a B+ Tree

Insertion on a B+ Tree


In this tutorial, you will learn about insertion operation on a B+ tree. Also, you will find working examples of inserting elements on a B+ tree in Python.

Inserting an element into a B+ tree consists of three main events: searching the appropriate leafinserting the element and balancing/splitting the tree.

Let us understand these events below.

Insertion Operation

Before inserting an element into a B+ tree, these properties must be kept in mind.

  • The root has at least two children.
  • Each node except root can have a maximum of m children and at least m/2 children.
  • Each node can contain a maximum of m – 1 keys and a minimum of ⌈m/2⌉ – 1 keys.

The following steps are followed for inserting an element.

  1. Since every element is inserted into the leaf node, go to the appropriate leaf node.
  2. Insert the key into the leaf node.


Case I

  1. If the leaf is not full, insert the key into the leaf node in increasing order.


Case II

  1. If the leaf is full, insert the key into the leaf node in increasing order and balance the tree in the following way.
  2. Break the node at m/2th position.
  3. Add m/2th key to the parent node as well.
  4. If the parent node is already full, follow steps 2 to 3.

Insertion Example

Let us understand the insertion operation with the illustrations below.

The elements to be inserted are 5,15, 25, 35, 45.

  1. Insert 5.
    Insert 5
    Insert 5
  2. Insert 15.
    Insert 15
    Insert 15
  3. Insert 25.
    Insert 25
    Insert 25
  4. Insert 35.
    Insert 35
    Insert 35
  5. Insert 45.
    Insert 45
    Insert 45

Python Examples

/* B+ tee in python */

import math

/* Node creation */
class Node:
    def __init__(self, order):
        self.order = order
        self.values = []
        self.keys = []
        self.nextKey = None
        self.parent = None
        self.check_leaf = False

    /* Insert at the leaf */
    def insert_at_leaf(self, leaf, value, key):
        if (self.values):
            temp1 = self.values
            for i in range(len(temp1)):
                if (value == temp1[i]):
                elif (value < temp1[i]):
                    self.values = self.values[:i] + [value] + self.values[i:]
                    self.keys = self.keys[:i] + [[key]] + self.keys[i:]
                elif (i + 1 == len(temp1)):
            self.values = [value]
            self.keys = [[key]]

/* B plus tree */
class BplusTree:
    def __init__(self, order):
        self.root = Node(order)
        self.root.check_leaf = True

    /* Insert operation */
    def insert(self, value, key):
        value = str(value)
        old_node =
        old_node.insert_at_leaf(old_node, value, key)

        if (len(old_node.values) == old_node.order):
            node1 = Node(old_node.order)
            node1.check_leaf = True
            node1.parent = old_node.parent
            mid = int(math.ceil(old_node.order / 2)) - 1
            node1.values = old_node.values[mid + 1:]
            node1.keys = old_node.keys[mid + 1:]
            node1.nextKey = old_node.nextKey
            old_node.values = old_node.values[:mid + 1]
            old_node.keys = old_node.keys[:mid + 1]
            old_node.nextKey = node1
            self.insert_in_parent(old_node, node1.values[0], node1)

    /* Search operation for different operations */
    def search(self, value):
        current_node = self.root
        while(current_node.check_leaf == False):
            temp2 = current_node.values
            for i in range(len(temp2)):
                if (value == temp2[i]):
                    current_node = current_node.keys[i + 1]
                elif (value < temp2[i]):
                    current_node = current_node.keys[i]
                elif (i + 1 == len(current_node.values)):
                    current_node = current_node.keys[i + 1]
        return current_node

    /* Find the node */
    def find(self, value, key):
        l =
        for i, item in enumerate(l.values):
            if item == value:
                if key in l.keys[i]:
                    return True
                    return False
        return False

    /* Inserting at the parent */
    def insert_in_parent(self, n, value, ndash):
        if (self.root == n):
            rootNode = Node(n.order)
            rootNode.values = [value]
            rootNode.keys = [n, ndash]
            self.root = rootNode
            n.parent = rootNode
            ndash.parent = rootNode

        parentNode = n.parent
        temp3 = parentNode.keys
        for i in range(len(temp3)):
            if (temp3[i] == n):
                parentNode.values = parentNode.values[:i] + 
                    [value] + parentNode.values[i:]
                parentNode.keys = parentNode.keys[:i +
                                                  1] + [ndash] + parentNode.keys[i + 1:]
                if (len(parentNode.keys) > parentNode.order):
                    parentdash = Node(parentNode.order)
                    parentdash.parent = parentNode.parent
                    mid = int(math.ceil(parentNode.order / 2)) - 1
                    parentdash.values = parentNode.values[mid + 1:]
                    parentdash.keys = parentNode.keys[mid + 1:]
                    value_ = parentNode.values[mid]
                    if (mid == 0):
                        parentNode.values = parentNode.values[:mid + 1]
                        parentNode.values = parentNode.values[:mid]
                    parentNode.keys = parentNode.keys[:mid + 1]
                    for j in parentNode.keys:
                        j.parent = parentNode
                    for j in parentdash.keys:
                        j.parent = parentdash
                    self.insert_in_parent(parentNode, value_, parentdash)

/* Print the tree */
def printTree(tree):
    lst = [tree.root]
    level = [0]
    leaf = None
    flag = 0
    lev_leaf = 0

    node1 = Node(str(level[0]) + str(tree.root.values))

    while (len(lst) != 0):
        x = lst.pop(0)
        lev = level.pop(0)
        if (x.check_leaf == False):
            for i, item in enumerate(x.keys):
            for i, item in enumerate(x.keys):
            if (flag == 0):
                lev_leaf = lev
                leaf = x
                flag = 1

record_len = 3
bplustree = BplusTree(record_len)
bplustree.insert('5', '33')
bplustree.insert('15', '21')
bplustree.insert('25', '31')
bplustree.insert('35', '41')
bplustree.insert('45', '10')


if(bplustree.find('5', '34')):
    print("Not found")

Insertion Complexity

Time complexity: Θ(t.logt n)

The complexity is dominated by Θ(logt n).

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.  

Google –> SETScholars