有一棵如下图所示的B-树(m=3),设计一个算法对其进行先序遍历(遍历到结点时直接输出结点中的关键字)和查找给定值的结点,要求写出B-树结点结构。
【正确答案】对B-树的线序遍历和查找算法与二叉排序树相应的算法相似。
实现本题功能的程序代码如下。
B-树结点的结构体定义如下:
typedef struct node
{
int n; //当前结点中关键字的个数
elemtype key[M];
struct node *ptr[M]; //M是已定义的常量
} btree;
查找:
btree *search(btree *b,elemtype x) //在b中查找值为x的结点
{
int i;
if(b!=NULL)
{
i=0;
while(i<b->n && x>b->key[i])
++i;
if(i==b->n)
return search(b->ptr[i],x);
else if(x==b->key[i]) //在b中找到了,则返回b
return b;
else
return search(b->ptr[i],x);
}
else
return NULL;
}
void inorder(btree *b)
{
int i;
if(b!=NULL)
{
for(i=0;i<b->n-1;++i)
cout<<b->key[i]<<",";
for(i=0;i<=b->n;++i)
inorder(b->ptr[i]);
}
}
【答案解析】