【问题标题】:Finding Minimum Key and Predecessor in B-Tree在 B-Tree 中找到最小键和前驱
【发布时间】:2013-07-08 01:05:13
【问题描述】:

解释如何找到存储在 B-tree 中的最小键以及如何找到存储在 B-tree 中的给定键的前任。

【问题讨论】:

    标签: algorithm b-tree array-algorithms


    【解决方案1】:

    找到最小键

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

    寻找前任

    • 首先通过从上到下递归遍历树找到给定元素
    • 那么有两种情况

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

    • 如果该元素没有留下子元素,则必须向上移动

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 最小将是最左边的孩子(或最左边的叶子节点)对吗?
      【解决方案3】:
      #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.
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-07
        • 1970-01-01
        • 2013-11-10
        • 2015-04-19
        • 1970-01-01
        • 1970-01-01
        • 2017-03-02
        • 2018-03-13
        相关资源
        最近更新 更多