简体   繁体   English

AVL 树查找最近的键

[英]AVL Tree find Closest Key

Find a String: X, which may or may not exist in the AVL tree.找到一个字符串:X,它可能存在也可能不存在于 AVL 树中。 Can i have the pseudo code to get X if it exists OR find the next biggest string after X?如果 X 存在,我可以使用伪代码来获取 X 或找到 X 之后的下一个最大字符串吗?

I have done the code for successor.我已经完成了继任者的代码。 Successor finds the next biggest node.继任者找到下一个最大的节点。

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
    }
  }

Example if the tree consist of numbers 1,2,3,4,7,9.例如,如果树由数字 1、2、3、4、7、9 组成。 If i want to find 6, it should return me 7 as 6 does not exists and the next biggest value is 7如果我想找到 6,它应该返回 7,因为 6 不存在并且下一个最大值是 7

You need a variant of search() function that returns either the nearest node, the next biggest or the last leaf node that was checked.您需要一个search()函数的变体,该函数返回最近的节点、下一个最大的节点或被检查的最后一个叶节点。 If it's the last leaf node, it won't be necessarily the nearest.如果它是最后一个叶节点,它不一定是最近的。 In your example, the last leaf node may be 2 or 9 for 6, not necessarily 4 or 7.在您的示例中,最后一个叶节点可能是 2 或 9 表示 6,不一定是 4 或 7。

A method that returns the next biggest can look like this.返回下一个最大的方法可能如下所示。

/* 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);
}

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

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