In the standard binary search tree, each new node is inserted somewhere at the bottom of the tree to replace an external node. This status is not an absolute requirement. You can also insert it from the root node by inserting it to the corresponding external node and then rotating it to the root node. The following shows the implementation:
# Include <stdio. h>
# Include <stdlib. h>
Struct tree
{
Int item;
Struct tree * l;
Struct tree * R;
};
Struct tree * rotr (struct tree * H)
{
If (H = NULL)
Return NULL;
Struct tree * x = NULL;
X = H-> L;
H-> L = x-> r;
X-> r = h;
Return X;
}
Struct tree * rotl (struct tree * H)
{
If (H = NULL)
Return NULL;
Struct tree * x = NULL;
X = H-> r;
H-> r = x-> L;
X-> L = h;
Return X;
}
Struct tree * insertt (struct tree * H, int item)
{
If (H = NULL)
{
H = malloc (sizeof (struct tree ));
If (H = NULL)
{
Printf ("malloc error \ n ");
Return NULL;
}
Else
{
H-> item = item;
H-> L = NULL;
H-> r = NULL;
Return h;
}
}
If (H-> item)
{
H-> L = insertt (H-> L, item );
H = rotr (h );
}
Else
{
H-> r = insertt (H-> r, item );
H = rotl (h );
}
Return h;
}
Void travel (struct tree * t)
{
If (t-> L! = NULL)
Travel (t-> L );
Printf ("% d \ n", T-> item );
If (t-> r! = NULL)
Travel (t-> r );
}
Int main (INT argc, char * argv [])
{
Struct tree * t = NULL;
T = insertt (T, 8 );
T = insertt (T, 7 );
T = insertt (T, 9 );
T = insertt (T, 6 );
T = insertt (T, 10 );
T = insertt (T, 5 );
T = insertt (T, 11 );
T = insertt (T, 4 );
T = insertt (T, 12 );
T = insertt (T, 3 );
T = insertt (T, 13 );
Travel (t );
Return 0;
}