Data Structures · Visualization
B-Tree: Insert
B-Tree
Inserting into a B-Tree finds the correct leaf, inserts the key in sorted order, and splits any node that overflows (exceeds 2t-1 keys), pushing the middle key up to the parent — splits can cascade all the way to the root. Time: O(log n). Space: O(log n) for the recursive split path.
Big-O: Search / insert / delete O(log n); each node holds many keys so the tree stays very shallow.
B-Tree: Insert
B-TreeInserting into a B-Tree finds the correct leaf, inserts the key in sorted order, and splits any node that overflows (exceeds 2t-1 keys), pushing the middle key up to the parent — splits can cascade all the way to the root.
How Insert Works
- Traverse from the root, choosing the child pointer between the two keys that bracket the new value, until reaching a leaf.
- Insert the key into the leaf in sorted position.
- If the leaf now holds more than 2t-1 keys, split it: the middle key moves up to the parent, and the leaf splits into two half-full nodes.
- If the parent also overflows from receiving the promoted key, repeat the split process upward.
- If the root itself splits, a new root is created, increasing the tree's height by one.
Insert Worked Example
Input: Insert 25 into a leaf [20,30,40] (order 3, max 3 keys) whose parent is [10,50]
- Leaf becomes [20,25,30,40] — overflow (4 keys)
- Split at median 30: left leaf [20,25], right leaf [40], 30 promoted
- Parent becomes [10,30,50] with the two new leaves attached
Output: Tree stays balanced; parent now has one extra key and one extra child
Press ▶ Run to watch it step by step.
def insert(root, key, t=2):
if len(root.keys) == 2 * t - 1: # root full → split
new_root = BNode()
new_root.children.append(root)
split_child(new_root, 0)
root = new_root
cur = root
while True:
i = len(cur.keys) - 1
while i >= 0 and key < cur.keys[i]:
i -= 1
i += 1
if cur.children:
if len(cur.children[i].keys) == 2 * t - 1:
split_child(cur, i) # split full child
cur = cur.children[i]
else:
cur.keys.insert(i, key) # leaf: insert here
return root
# split_child promotes the middle key upward
# example: insert 25Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Insert Time & Space Complexity
When to Use Insert
- Bulk-loading database indexes
- Append-heavy log-structured storage indexes
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.