二进制搜索树 - 按两个数据项排序

时间:2014-03-05 16:22:24

标签: c++ binary-tree binary-search-tree

我想维护两个相关的二进制搜索树,其节点包含两项数据 - 一个页码和一个创建/引用的时间(细节并不重要 - 基本上它是两个64位数字)。 / p>

第一棵树按页码排序,第二棵树按创建时间排序 - 基本上用例是:

  • 查找页面是否存在(位于树中),按页码搜索
  • 如果页面存在,请将其参考时间更新为
  • 如果页面不存在 - 将页面添加到两棵树中,创建时间为现在
  • 但是,在上述情况下,如果树已达到最大容量,则删除具有最早参考时间的页面

我尝试这样做的方法是按页码搜索第一个树 - 因此我们返回一个也有创建/参考时间记录的节点,然后在第二个树中搜索同时具有该值的节点参考时间,是那个页面。

困难在于参考时间可能不是唯一的(这是绝对障碍):我是否可以在节点中实现一种算法,允许我在树中搜索以找到正确的节点而不破坏树代码...

这个树代码现在......

template <typename NODE> NODE* redblacktree<NODE>::locatenode(NODE* v,
    NODE* node) const
{
if (node == NULL)
    return node;
if (v->equals(node))
    return node;
if (v->lessthan(node))
    return locatenode(v, node->left);
else
    return locatenode(v, node->right);
}

这是节点端的一个简单(工作)单一搜索代码段,用于单个索引值:

bool PageRecord::operator==(PageRecord& pRecord) const
{
return (pageNumber == pRecord.getPageNumber());
}

bool PageRecord::operator<(PageRecord& pRecord) const
{
return (pageNumber < pRecord.getPageNumber());
}

1 个答案:

答案 0 :(得分:1)

更改NODE数据结构以允许节点中的多个页面。

typedef struct node
{
    int choice;  // if 1 then page tree, if 0 then reference tree
    vector<Page> pg;  // if choice=0
    Reference ref;  // if choice=1

    struct node* left;
    struct node* right;
}NODE;

您可以相应地修改equalslessthan功能。 locatenode功能保持不变。


我将添加一些关于此处使用的数据结构的内容。实际上,您不需要树来维护引用。只有在以下情况下才需要参考:

  • If the page exists, update its reference time to now
  • But, in the case above, if the tree has reached maximum capacity delete a page with the oldest reference time

所以这也可以使用堆来完成。优点是,然后插入操作仅花费O(1)时间。

对于第一点,如果必须更新引用,则节点在堆中向下移动。因此,保持从页面树到引用堆的链接。并继续交换参考堆中的节点,直到当前节点进入最后一级。 O(logn)时间。

对于第二点,删除堆的第一个节点。 O(logn)来这里。

至于If the page does not exist - add the page to both trees with a creation time of now,在堆的末尾添加新节点。 O(1)时间。

相关问题