[英]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.