[英]AVL Tree find Closest Key
找到一个字符串: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
您需要一个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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.