【问题标题】:Range function for values in a splay tree?展开树中值的范围函数?
【发布时间】:2019-03-15 00:46:00
【问题描述】:

我是数据结构的初学者。 我正在尝试为具有展开树的范围函数编写一些伪代码:Range(S, A, B),它将 S 更改为键值 C 满足 A ≤ C ≤ B 的所有成员的集合。我知道展开树的存在类型的二叉搜索树并实现自己的展开操作。基本上,我试图返回介于 A 和 B 之间的一系列值。但是,我无法理解我应该如何执行此操作,或者我什至应该从哪里开始,以及我应该检查哪些条件。我已经阅读了展开树的定义,并且知道它们就像具有移至前端算法的二叉搜索树。

这是我目前所拥有的:

Algorithm Range(Array S, int A, int B): array Set
S = new array(size) //Initialize an empty array of some size
if (A > B) then return NULL

在这一点之后,我感到有些失落。我不确定如何检查伸展树的值。请让我知道我是否可以提供更多信息,或者我应该去什么方向。

【问题讨论】:

    标签: algorithm data-structures binary-search-tree pseudocode splay-tree


    【解决方案1】:

    根据Wikipedia

    展开树是一种自我调整的二叉搜索树,具有最近访问的元素可以快速再次访问的附加属性。它在 O(log n) 摊销时间内执行插入、查找和删除等基本操作。

    但是,由于“splay”操作仅适用于随机搜索,因此可以将树视为普通的“二叉搜索树”。

    算法变成,

    Range (BSTree T, int A, int B)
      int Array S
    
      S ← Empty array
      If A <= B then
        For each C in T
          If A <= C and C <= B then
            Append C to S
      Return S
    

    即依次遍历树T;并且,对于每个满足条件的项C,将该项添加到数组S中。如果没有项满足条件,则返回一个空数组。

    For each,如果在实现语言中不可用,可以使用描述为in-order的算法实现

    inorder(node)
      if (node = null)
        return
      inorder(node.left)
      visit(node)
      inorder(node.right)
    

    其中vist(node)是测试物品是否满足条件的地方。

    【讨论】:

      【解决方案2】:

      这已经很晚了,但是从问题提示中的“更改”一词来看,它似乎是在要求您修改 S 树,使其仅包含范围内的元素。

      所以我会这样做:围绕下限展开树,并删除左子树,因为左子树中的所有内容都将低于下限。然后围绕上限展开树,然后丢弃右子树,因为右子树中的所有内容都将高于上限。

      下面是我用伪代码编写它的方式

      //assumes S is the root of an actual tree with elements
      function Range(node S, int A, int B)
          node temp <- Splay(k1, S) //splay around lower bound
          if (temp.key < k1) //makes sure that there are elements in tree that satisfies this
              temp <- temp.right
              if (temp == null) return //there are no key greater than A, abort!
              temp <- Splay(temp.key, S)
      
          temp.left <- null //drops left subtree, bc they are all going to be lesser value
          temp <- Splay(k2, temp) //splay around upper bound
          if (temp.key > k2)
              temp <- temp.left
              if (temp == null) return //there are no keys less than B, abort!
              temp <- Splay(temp.key, temp)
      
          temp.right <- null //drops all right subtree
          S <- temp
      

      希望这会有所帮助!这也应该在 O(logn) 中运行

      【讨论】:

      • 如果只给你一个范围,你能告诉我你在哪个节点展开?当您编写 Splay(k1,S) 时,您会展开根节点吗?还有什么是k1?
      猜你喜欢
      • 2011-11-20
      • 2022-11-12
      • 2014-07-28
      • 1970-01-01
      • 2011-07-06
      • 2020-04-20
      • 2017-05-17
      相关资源
      最近更新 更多