2-3树简介
2-3树是最简单的B-树(或-树)结构,其每个非叶节点都有两个或三个子女,而且所有叶都在统一层上。
2-3树的模拟过程可以看链接:InsertSortion
实现过程
在2-3树中,一个结点只有一个值的我们称为2-结点,有两个值的称为3-结点,在2-3树中,一个结点最多只有两个值,即3-结点。
什么时候我们认为2-3树不平衡呢?就是任意一个结点到最后每个结点的距离都相等。
当结点变成4-结点的时候,总共会有6种情况:
所以针对每一种情况,我们一一实现就可以实现2-3树了。
代码实现
ADT :
typedef struct node {
int a[3]; //a[2],作为4-结点时的缓存
int num; //数组a的长度:1,2,3
struct node *left_child;
struct node *mid_child;
struct node *right_child;
struct node *tmp_child; //作为4-结点时的缓存
struct node *parent;
} Btree, *BtreePtr;
void exchange(int *a, int *b);
BtreePtr _node(const int key); //create a node
void _sort(BtreePtr b); //sort a[]
BtreePtr _checkNum(BtreePtr p); //balance
BtreePtr _insertBTree(BtreePtr b, const int key, const int pos); //insert key
BtreePtr insertBTree(BtreePtr root, const int key, const int pos); //initial
void freeTree(BtreePtr p);
int BTreeSearch(const int *a, const int length, const int key) ;
完整代码:
#include <stdio.h>
#include <malloc.h>
#include <memory.h>
#define NUM(p) ((p==NULL)?0:p->num)
typedef struct node {
int a[3<