To understand this code, you must understand the single rotation and double rotation algorithms. Second, we need to really understand recursive usage.
[Html]
/*
* Avl tree.
*/
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
Struct AvlNode;
Typedef struct AvlNode * Position;
Typedef struct AvlNode * AvlTree;
Struct AvlNode
{
Int Element;
AvlTree Left;
AvlTree Right;
Int Height;
};
Int Max (int a, int B)
{
Return (a> B )? A: B;
}
Static int HeightAvl (Position P)
{
If (P = NULL)
{
Return-1;
}
Else
{
Return P-> Height;
}
}
Static Position SingleRotateWithLeft (Position K2)
{
Position K1;
K1 = K2-> Left;
K2-> Left = K1-> Right;
K1-> Right = K2;
K2-> Height = Max (HeightAvl (K2-> Left), HeightAvl (K2-> Right) + 1;
K1-> Height = Max (HeightAvl (K1-> Left), HeightAvl (K2-> Right) + 1;
Return K1;
}
Static Position SingleRotateWithRight (Position K2)
{
Position K1;
K1 = K2-> Right;
K2-> Right = K1-> Left;
K1-> Left = K2;
K2-> Height = Max (HeightAvl (K2-> Left), HeightAvl (K2-> Right) + 1;
K1-> Height = Max (HeightAvl (K1-> Left), HeightAvl (K2-> Right) + 1;
Return K1;
}
Static Position DoubleRotateWithLeft (Position K3)
{
K3-> Left = SingleRotateWithRight (K3-> Left );
Return SingleRotateWithLeft (K3 );
}
Static Position DoubleRotateWithRight (Position K3)
{
K3-> Left = SingleRotateWithLeft (K3-> Left );
Return SingleRotateWithRight (K3 );
}
AvlTree InsertAvl (int X, AvlTree T)
{
If (T = NULL)
{
T = (AvlTree) malloc (sizeof (AvlTree ));
If (T = NULL)
{
Printf ("out of space !!! \ N ");
}
Else
{
T-> Left = NULL;
T-> Right = NULL;
}
T-> Element = X;
T-> Height = 0;
}
Else if (X <T-> Element)
{
T-> Left = InsertAvl (X, T-> Left );
If (HeightAvl (T-> Left)-HeightAvl (T-> Right) = 2)
{
If (X <T-> Left-> Element)
{
T = SingleRotateWithLeft (T );
}
Else
{
T = DoubleRotateWithLeft (T );
}
}
}
Else if (X> T-> Element)
{
T-> Right = InsertAvl (X, T-> Right );
If (HeightAvl (T-> Right)-HeightAvl (T-> Left) = 2)
{
If (X> T-> Right-> Element)
{
T = SingleRotateWithRight (T );
}
Else
{
T = DoubleRotateWithRight (T );
}
}
}
T-> Height = Max (HeightAvl (T-> Left), HeightAvl (T-> Right) + 1;
Return T;
}
Int main (void)
{
AvlTree;
InsertAvl (1, Tree );
}
From angelbosj's column