Find a String: X, which may or may not exist in the AVL tree. Can i have the pseudo code to get X if it exists OR find the next biggest string after 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. If i want to find 6, it should return me 7 as 6 does not exists and the next biggest value is 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. 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.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.