|
p = inserted node; // p is for sure balanced...
while ( p != root )
{
p = p.parent; // traverse twards the root
if ( p is unbalanced )
{
/* -----------------------------------------------
Identify node x for the restructure operation
----------------------------------------------- */
z = p;
y = the taller Child of z;
x = the taller Child of y;
p = restructure( x );
}
}
|
Example:
|
Example execution of the Re-balance algorithm:
p = inserted node (46)
while loop:
p = p.parent (48)
p (48) is balanced
p = p.parent (50)
p (50) is balanced
p = p.parent (78)
p (78) is unbalanced
z = (78)
y = (50)
x = (48)
p = rebalance( x (48) )
|
protected void rebalance(Position<Entry<K,V>> zPos)
{
if ( isInternal(zPos) )
setHeight(zPos); // update height of node
while ( ! isRoot(zPos) )
{ // traverse up the tree towards the root
zPos = parent(zPos);
setHeight(zPos); // update height of node
if ( ! isBalanced(zPos) )
{
/* --------------------
Find x
-------------------- */
Position<Entry<K,V>> xPos = tallerChild(tallerChild(zPos));
zPos = restructure(xPos); // tri-node restructure
setHeight(left(zPos)); // recompute heights
setHeight(right(zPos));
setHeight(zPos);
}
}
}
|
|
Therefore:
|
|
/**
* Inserts an item into the AVL Tree and returns the newly created
* entry.
*/
public Entry<K,V> insert(K k, V v) throws InvalidKeyException
{
Entry<K,V> toReturn = super.insert(k, v); // insert into a binary search tree
/* ---------------------------------------------------------
Note: super.insert(k,v) update the "actionPos" variable
actionPos = inserted node
---------------------------------------------------------- */
rebalance(actionPos); // rebalance up from the insertion position
return toReturn; // Return a reference to the inserted node
}
|
|
|