tags:

views:

60

answers:

1

Say I have a B-Tree with nodes in a 3-4 configuration (3 elements and 4 pointers). Assuming I build up my tree legally according to the rules, is it possible for me to reach a situation where there are two nodes in a layer and one node has 4 exiting pointers and the other has only two exiting pointers?

In general, what guarantees do I have as to the balancedness of a properly used B-Tree

+3  A: 

The idea behind balance (in general balanced tree data structures) is that the difference in depths between any two sub-trees is zero or one (depending on the tree). In other words, the number of comparisons used to find a leaf node is always similar.

So yes, you can end up in the situation you describe, simply because the depths are the same. The number of elements in each node is not a concern to the balance (but see below).

This is perfectly legal even though there's more items in the left node than the right (null pointers are not shown):

                 +---+---+---+
                 | 8 |   |   |
                 +---+---+---+
        ________/    |
       /             |
      |              |
+---+---+---+  +---+---+---+
| 1 | 2 | 3 |  | 9 |   |   |
+---+---+---+  +---+---+---+

However, it's very unusual to have a 3-4 BTree (some would actually say that's not a BTree at all, but some other data structure).

With BTrees, you usually have an even number of keys as maximum in each node (e.g., a 4-5 tree) so that the splitting and combining is easier. With a 4-5 tree, the decision as to which key is promoted when a node fills up is easy - it's the middle one of the five. That's not such a clear-cut matter with a 3-4 tree since it could be one of two (there is no definite middle for four elements).

It also allows you to follow the rule that your nodes should contain between n and 2n elements. In addition (for "proper" BTrees), the leaf nodes are all at the same depth, not just within one of each other.

If you added the following values to an empty BTree, you could end up with the situation you describe:

1            1

2            1,2

5            1,2,5

6            1,2,5,6

7               5
               / \
            1,2   6,7

8               5
               / \
            1,2   6,7,8

9               5
               / \
            1,2   6,7,8,9
paxdiablo