Notes From CS Undergrad Courses FSU
This project is maintained by awa03
Overhead
Advantage
![[scrnli_10_23_2023_5-48-40 PM.png]]
[!Important] Must Maintain Balance! This can be done through shifting the formation of the tree as shown above
struct AvlNode
{
Comparable element;
AvlNode *left;
AvlNode *right;
int height;
AvlNode( const Comparable & ele, AvlNode *lt, AvlNode *rt, int h = 0 )
: element{ ele }, left{ lt }, right{ rt }, height{ h } { }
AvlNode( Comparable && ele, AvlNode *lt, AvlNode *rt, int h = 0 )
: element{ std::move( ele ) }, left{ lt }, right{ rt }, height{ h } { }
};
/**
* Return the height of node t or -1 if nullptr.
*/
int height( AvlNode *t ) const
{
return t == nullptr ? -1 : t->height;
}
/* Internal method to insert into a subtree.
* x is the item to insert.
* t is the node that roots the subtree.
* Set the new root of the subtree.
*/
void insert( const Comparable & x, AvlNode * & t )
{
if( t == nullptr )
t = new AvlNode{ x, nullptr, nullptr };
else if( x < t->element )
insert( x, t->left );
else if( t->element < x )
insert( x, t->right );
balance( t );
}
// Assume t is balanced or within one of being balanced
void balance( AvlNode * & t )
{
if( t == nullptr )
return;
if( height( t->left ) - height( t->right ) > ALLOWED_IMBALANCE )
if( height( t->left->left ) >= height( t->left->right ) )
rotateWithLeftChild( t );
else
doubleWithLeftChild( t );
else
if( height( t->right ) - height( t->left ) > ALLOWED_IMBALANCE )
if( height( t->right->right ) >= height( t->right->left ) )
rotateWithRightChild( t );
else
doubleWithRightChild( t );
t->height = max( height( t->left ), height( t->right ) ) + 1;
}
void rotateWithLeftChild(AVLNode * &k2){
AVLNode * k1 = k2->left;
k2->left = k1->right;
k1->right = k2;
k2->height = max( height(k2->left), height( k2->right)) +1;
k1->height = max( k1->left ), k2->height) + 1;
k2 = k1;
}
void doubleWithLeftChild(AVLNode * & k3){
rotateWithRightChild(k3->left);
rotateWithLeftChild(k3);
}
T1, T2, T3 and T4 are subtrees.
z y
/ \ / \
y T4 Right Rotate x z
/ \ - - - - - > / \ / \
x T3 T1 T2 T3 T4
/ \
T1 T2