# B-Tree和B+Tree

### B-Tree

d为大于1的一个正整数，称为B-Tree的度。

h为一个正整数，称为B-Tree的高度。

key和指针互相间隔，节点两端是指针。

BTree_Search(node, key) {
if(node == null) return null;
foreach(node.key)
{
if(node.key[i] == key) return node.data[i];
if(node.key[i] > key) return BTree_Search(point[i]->node);
}
return BTree_Search(point[i+1]->node);
}
data = BTree_Search(root, my_key);

The height of a B-Tree:

Number of disk accesses on a B-tree is often proportional to the B-tree height.

Theorem 18.1

If n ≥ 1 then h ≤ logt (n + 1)/2                                                     Note:  log2t n ≤ logt n

for any n-keyB-Tree T of height h, and minimum degree t ≥ 2:

2t-1 is maximum number of keys

2t is the maximum number of children

t-1 is the minimum number of keys

t is the minimum number of children

Proof

By B-tree definition, root contains at least one key and all other nodes at least t-1 keys.

t-1 key node must have t children nodes.

Root has at least 1 key

• depth 0 root 1 node with at least 1 key
• depth 1 at least 2 nodes with at least t-1 keys
• depth 2 at least 2t nodes with at least t-1 keys
• depth 3 at least 2t2 nodes with at least t-1 keys

:

• depth h at least 2th-1 nodes

The number n of keys satisfies (by A. 5 of text):

• 1 is the root key
• t-1 is minimum keys per node of non-root nodes
• summation of total number of non-root nodes

Theorem 18.1 Proof

 n ≥ 2th-1 (n+1)/2 ≥ th th ≤ (n+1)/2 logt th ≤ logt (n+1)/2 h ≤ logt (n + 1)/2

Example

t = 2, n = 65536

h ≤ log2 (65536 + 1)/2 = log2 32768 = log2 215 = 15

t = 8, n = 65536

h ≤ log8 (65536 + 1)/2 = log8 32768 = log8 85 = 5

### B+Tree

B-Tree有许多变种，其中最常见的是B+Tree，例如MySQL就普遍使用B+Tree实现其索引结构。

### 带有顺序访问指针的B+Tree

B+树的分裂：当一个结点满时，分配一个新的结点，并将原结点中1/2的数据复制到新结点，最后在父结点中增加新结点的指针；B+树的分裂只影响原结点和父结点，而不会影响兄弟结点，所以它不需要指向兄弟的指针。

B*树的分裂：当一个结点满时，如果它的下一个兄弟结点未满，那么将一部分数据移到兄弟结点中，再在原结点插入关键字，最后修改父结点中兄弟结点的关键字（因为兄弟结点的关键字范围改变了）；如果兄弟也满了，则在原结点与兄弟结点之间增加新结点，并各复制1/3的数据到新结点，最后在父结点增加新结点的指针。

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120