b树节点分割技术

B-Tree Node Splitting Techniques

本文关键字:技术 分割 树节点      更新时间:2023-10-16

我在做我的DSA(数据结构和算法)作业时偶然发现了一个问题。我说要实现一个带有插入和搜索算法的b树。到目前为止,搜索工作正常,但我在实现插入函数时遇到了麻烦。特别是b树节点分割算法背后的逻辑。我能想到的伪代码/c风格如下:

    #define D 2
    #define DD 2*D
    typedef btreenode* btree;
    typedef struct node
    {
        int keys[DD];  //D == 2 and DD == 2*D;
        btree pointers[DD+1];
        int index; //used to iterate throught the "keys" array
    }btreenode;
    void splitNode(btree* parent, btree* child1, btree* child2)
    {
        //Copies the content from the splitted node to the children
        (*child1)->key[0] = (*parent)->key[0];
        (*child1)->key[1] = (*parent)->key[1];
        (*child2)->key[0] = (*parent)->key[2];
        (*child2)->key[1] = (*parent)->key[3];
        (*child1)->index = 1;
        (*child2)->index = 1;
        //"Clears" the parent node from any data
        for(int i = 0; i<DD; i++) (*parent)->key[i] = -1;
        for(int i = 0; i<DD+1; i++) (*parent)->pointers[i] = NULL
        //Fixed the pointers to the children
        (*parent)->index = 0;
        //the line bellow was taken out for creating a new node  that didn't have to be there.
        //(*parent)->key[(*parent)->index] = newNode(); // The newNode() function allocs and inserts a the new key that I need to insert.
        (*parent)->pointers[index] = (*child1);
        (*parent)->pointers[index+1] = (*child2);
    }

我几乎可以肯定我在指针上搞砸了什么,但我不确定是什么。任何帮助都是感激的。也许我需要在b树这门课上多学一点?我必须补充一点,虽然我可以使用c++的基本输入/输出,但我需要使用C风格的结构体。

您不需要在这里创建新节点。显然,您已经创建了两个新的子节点。在填充子节点之后,你所要做的就是让父节点指向两个子节点,通过复制每个子节点的第一个键,并将它的键数调整为2。您也不需要将父键设置为-1。