繁体   English   中英

在B树中查找最小密钥和前任

[英]Finding Minimum Key and Predecessor in B-Tree

说明如何找到存储在B树中的最小密钥,以及如何找到存储在B树中的给定密钥的前身。

查找最小密钥

  • 递归转到最左边的孩子,直到找到NULL

寻找前辈

  • 通过递归遍历树的顶部,首先找到给定的元素
  • 然后有两种情况

  • 如果该元素具有左子元素,请在以该左子元素为根的子树中找到最大的子元素

  • 如果该要素还没有留下孩子,那么您必须向上

您可以编写递归函数,以通过每个父节点的左右节点遍历B树(从根开始)。 在此期间,您可以比较所有值并找到最小值及其父节点。

#define BT_T 3// degree of B-tree
#define INF -32768

//struct of a node of B-tree
struct bnode {
    int num;//number of keys in a bnode
    int leaf; //1 for leaf,0 for not leaf
    int value[2*BT_T -1]; //suppose all the key in B-tree is positive.
    struct bnode *child[2*BT_T];
};

//minimum is the most left leaf's first value.
int find_min(struct bnode *p) {
    if(p==NULL)
        return -1;
    if(!p->leaf)
        find_min(p->child[0]);
    else
        return p->value[0];
}

//a predecessor's candidate of a given key are less than the key.
//the predecessor among the candidate is the largest one of them.
int find_predecessor(struct bnode *node,int val) {
    int i,temp,max = INF;
    for(i=0;i<num-1;i++) {
        if(node->value[i] >= val)
            break;
        if(max > node->value[i]) {
            max = ->value[i];
            temp = find_predecessor(node->child[i],val);
    max = (temp>max?temp:max);
        }
    }
    return max;
    //when there is no predecess,max is INF.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM