Sub topic 15
B+ tree search, range queries, insertion and deletion
This chapter assumes you know the B+ tree layout from the previous chapter. Internal nodes hold only separator keys and tree pointers. Leaves hold every key with its record pointer and are chained by next-leaf pointers. You should also be comfortable with ceiling and floor arithmetic and with the block-access cost model.
Conventions used here
GATE questions state their own convention, and you should always follow the question. This chapter uses the following.
- An internal node of order p has at most p children and at most p-1 keys.
- A leaf holds at most L keys. In many questions L = p-1.
- A non-root internal node has at least ceil(p/2) children.
- A non-root leaf has at least ceil(L/2) keys.
- The root may have as few as 2 children (if it is internal) or 1 key (if it is a leaf).
- A separator key in an internal node is a copy of the smallest key in the subtree to its right. A key equal to a separator therefore goes to the right child.
Search
Search follows exactly one root-to-leaf path. At each internal node, find the first separator greater than the search key and follow the pointer just before it. At the leaf, look for the key. Every search ends at a leaf, even if the key also appears in an internal node.
If the tree has h levels, including the leaf level, a search costs h block accesses. If the leaf stores record pointers, add 1 access for the data block. All searches cost the same, which is a difference from B-trees, where a key may be found early.
Range queries
A range query such as key BETWEEN lo AND hi has two phases.
- Search for
loto reach its leaf. This costs h accesses. - Walk the next-leaf pointers, collecting keys, until you see a key greater than
hior reach the last leaf.
The cost is h plus the number of additional leaf blocks read. The scan never returns to the internal nodes, and this is the main reason databases prefer B+ trees.
from bisect import bisect_right
class Node:
def __init__(self, keys, children=None, records=None):
self.keys = keys
self.children = children
self.records = records
self.next = None # next leaf, leaves only
def find_leaf(root, key):
reads = 1 # the root block
node = root
while node.children is not None:
node = node.children[bisect_right(node.keys, key)]
reads += 1
return node, reads
def range_query(root, lo, hi):
leaf, reads = find_leaf(root, lo)
out = []
while leaf is not None:
for k in leaf.keys:
if k > hi:
return out, reads
if k >= lo:
out.append(k)
leaf = leaf.next
if leaf is not None:
reads += 1
return out, reads
a = Node([10, 20], records=["r10", "r20"])
b = Node([30, 40], records=["r30", "r40"])
c = Node([50, 60], records=["r50", "r60"])
d = Node([70, 80], records=["r70", "r80"])
a.next, b.next, c.next = b, c, d
root = Node([30, 50, 70], children=[a, b, c, d])
print(range_query(root, 35, 65))The output is ([40, 50, 60], 4). The root is read, then leaf B, then leaves C and D. Leaf D is read only to discover that 70 is past the upper bound.
Insertion
- Search for the leaf where the key belongs.
- If the leaf has room, insert the key in sorted position. Done.
- If the leaf overflows (L+1 keys), split it into two leaves. The left leaf keeps the first ceil((L+1)/2) keys. The right leaf gets the rest. Fix the next-leaf pointers.
- Copy the smallest key of the new right leaf into the parent. The key stays in the leaf as well.
- If the parent now has p keys (one too many), split it. The middle key moves up to the grandparent and is not kept in either half.
- Repeat upward. If the root splits, create a new root with one key. This is the only way the tree grows taller.
The leaf split copies a key up. The internal split pushes a key up. Confusing the two is a common error.
Worked example
Take leaf capacity L = 3 and order p = 4 (3 keys per internal node). Insert 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 in order.
- After 10, 20, 30, the root is a single leaf
[10 20 30]. - Inserting 40 overflows. Split into
[10 20]and[30 40], and copy 30 up. The root is[30]. - Inserting 50 gives
[30 40 50]. Inserting 60 overflows, so split into[30 40]and[50 60]and copy 50 up. The root is[30 50]. - Inserting 70 and 80 splits
[50 60 70 80]into[50 60]and[70 80]and copies 70 up. The root is[30 50 70], which is full. - Inserting 90 gives
[70 80 90]. Inserting 100 splits it into[70 80]and[90 100]and copies 90 up. The root would be[30 50 70 90], which has 4 keys and overflows. - Split the root. Keys 30 and 50 stay on the left, key 90 goes right, and 70 moves up into a new root.
The tree has height 3. The key 70 appears both in the root and in leaf D. Searching for 80 compares against 70 at the root, goes right, compares against 90, goes left, and finds 80 in D.
Deletion
- Search for the leaf and remove the key.
- If the leaf still has at least ceil(L/2) keys, stop. The separator in a parent may still equal the deleted key. That is legal, because it still separates the subtrees correctly. Some textbooks replace it, and GATE answers usually do not depend on it.
- If the leaf underflows, try to borrow from an adjacent sibling that has more than the minimum. Move one key across and update the parent separator to the new smallest key of the right node.
- If no sibling can lend, merge the leaf with a sibling. Remove the separator between them from the parent.
- If the parent underflows, repeat the same borrow-or-merge steps there. When an internal node borrows, the key rotates through the parent. When two internal nodes merge, the parent separator is pulled down into the merged node.
- If the root is left with one child, that child becomes the new root, and the tree shrinks by one level.
| Situation | Action | Effect on parent |
|---|---|---|
| Leaf has more than the minimum after deletion | Remove the key | None needed |
| Leaf underflows, sibling has a spare key | Borrow | Separator changes to the new smallest key of the right leaf |
| Leaf underflows, siblings are at minimum | Merge | One separator and one pointer removed |
Borrow example: leaves [10 20 30] and [40 50] have separator 40. Delete 50, leaving [40], which underflows because the minimum is 2. The left leaf can lend, so 30 moves over. The leaves become [10 20] and [30 40], and the separator becomes 30.
Merge example: in the tree above, delete 20. Leaf A becomes [10] and underflows. Its only sibling B has exactly 2 keys and cannot lend. Merge to get [10 30 40], which fits in 3 slots. Remove the separator 30 from the parent, which becomes [50] with 2 children. That is still valid.
Costs
| Operation | Block accesses (tree height h) |
|---|---|
| Search | h, plus 1 for the data block |
| Range query returning keys in k leaves | h + (k - 1) leaf reads, plus data blocks |
| Insert, no split | h reads, 1 write |
| Insert with splits | Up to h reads and about 2h + 1 writes, from splitting every level |
| Delete | h reads, plus sibling reads and merge writes |
Exercise
In a B+ tree whose leaves hold at most 3 keys and at least 2, one leaf holds [50 60] and its right neighbour holds [70 80]. Delete 50. What happens at the leaf level, and what changes in the parent?
Show answer
Leaf [50 60] becomes [60], which has 1 key and underflows. The right sibling [70 80] has exactly the minimum, so it cannot lend. The two leaves merge into [60 70 80], which fits in 3 slots. The separator between them (70) is removed from the parent, along with one pointer. The parent may then underflow and need its own borrow or merge.
Exercise
A B+ tree has 3 levels, including the leaf level. A range query returns keys that lie in 5 consecutive leaves. How many index block accesses are needed, ignoring data blocks?
Show answer
The search for the lower bound reads the root, one internal node and the first leaf, which is 3 accesses. The scan follows next-leaf pointers to 4 more leaves. The total is 3 + 4 = 7 accesses.