Btree
A B-tree is a self-balancing tree data structure that maintains sorted data and allows for efficient insertion, deletion, and search operations. It is commonly used in databases and file systems.
Key Properties of B-trees
Balanced Tree: All leaf nodes are at the same depth.
Node Structure: Each node contains multiple keys and children pointers.
Order: The maximum number of children a node can have is defined by the order
mof the B-tree.Key Constraints:
Each node can have at most
m-1keys.Each node (except the root) must have at least
ceil(m/2) - 1keys.
Children Constraints:
Each internal node can have at most
mchildren.Each internal node (except the root) must have at least
ceil(m/2)children.
Operations
Search
To search for a key in a B-tree:
Start at the root node.
Perform a binary search within the node to find the range of keys.
If the key is found, return it.
If the key is not found and the node is a leaf, the key does not exist.
If the key is not found and the node is an internal node, recursively search the appropriate child.
Insertion
To insert a key into a B-tree:
Find the appropriate leaf node where the key should be inserted.
Insert the key into the leaf node in sorted order.
If the node overflows (i.e., it has
mkeys), split the node:Create a new node and move the median key to the parent.
Distribute the remaining keys and children between the two nodes.
If the parent node overflows, recursively split the parent.
Deletion
To delete a key from a B-tree:
Find the node containing the key.
If the key is in a leaf node, remove it directly.
If the key is in an internal node:
If the predecessor or successor child has at least
ceil(m/2)keys, replace the key with the predecessor or successor and delete the key from the child.If both children have fewer than
ceil(m/2)keys, merge the key and its children.
If a node underflows (i.e., it has fewer than
ceil(m/2) - 1keys), rebalance the tree by borrowing a key from a sibling or merging with a sibling.
Example
Consider a B-tree of order 3 (each node can have at most 2 keys and 3 children).
Initial Tree
Insertion of 25
Insert 25 into the appropriate leaf node.
The node [15, 20] overflows, so split it:
Move 20 to the parent.
Create a new node [25].
Deletion of 10
Find 10 in the root node.
Replace 10 with its successor (15).
Delete 15 from the leaf node.
This example illustrates the basic operations of a B-tree, including insertion and deletion, while maintaining balance and order.