【问题标题】:AVL Tree find Closest KeyAVL 树找到最近的键
【发布时间】:2015-09-11 09:24:02
【问题描述】:

找到一个字符串:X,它可能存在也可能不存在于 AVL 树中。如果 X 存在或找到 X 之后的下一个最大字符串,我可以使用伪代码获取 X 吗?

我已经完成了后继者的代码。继任者找到下一个最大的节点。

protected BSTVertex successor(BSTVertex T) 
  {
    if (T.right != null)                       // this subtree has right subtree
      return findMin2(T.right);  // the successor is the minimum of right subtree
    else {
      BSTVertex par = T.parent;
      BSTVertex cur = T;
      // if par(ent) is not root and cur(rent) is its right children
      while ((par != null) && (cur == par.right)) {
        cur = par;                                         // continue moving up
        par = cur.parent;
      }
      return par == null ? null : par;           // this is the successor of T
    }
  }

例如,如果树由数字 1、2、3、4、7、9 组成。如果我想找到 6,它应该返回 7,因为 6 不存在,下一个最大值是 7

【问题讨论】:

  • x 是什么,你卡在哪里了?
  • 嗨,我的意思是给定一个字符串,在 avl 树中找到该字符串,或者如果找不到该字符串,则查找下一个最大的最接近匹配项

标签: java avl-tree


【解决方案1】:

您需要一个search() 函数的变体,它返回最近的节点、下一个最大的节点或检查的最后一个叶节点。如果它是最后一个叶子节点,它不一定是最近的。在您的示例中,最后一个叶节点可能是 2 或 9 表示 6,不一定是 4 或 7。

返回下一个最大的方法可能如下所示。

/* returns the next biggest or null. If it's null, the first is the next biggest
\. */
BSTVertex searchOrNextBiggest(BSTVertex T, int key) {
    /* this.nextBiggest is the next biggest so far */
    if (T == null) return this.nextBiggest;
    else if (T.key == key) return T;

    /* is this the next biggest */
    if (T.key - key > 0 &&
        (this.nextBiggest == null ||
         T.key - key < this.nextBiggest.key - key))
        this.nextBiggest = T;

    if (T.key < key) return searchOrNextBiggest(T.left, key);
    else             return searchOrNextBiggest(T.right, key);
}

【讨论】:

    猜你喜欢
    • 2018-03-31
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多