题目描述:inserting some numbers into an initially empty AVL tree.Show AVL tree in preorder.
#include <stdio.h>
#include <stdlib.h>
struct Node;
typedef struct Node *ptrtoNode;
typedef ptrtoNode position;
typedef ptrtoNode tree;
struct Node
{
int x;
position left, right;
int height;
};
/
int max(int x1, int x2);
int height(tree T);
position singleRotatewithLeft(position k2);
position singleRotatewithRight(position k2);
position doubleRotatewithLeft(position k3);
position doubleRotatewithRight(position k3);
tree insert(int x, tree T);
void preOrderTraverse(tree T);
/
int main()
{
char x;
int number;
tree T = NULL;
while ((x = getchar()) != '\n' && x != EOF)
{
if (x != ',')
{
number = x - '0';
T = insert(number, T);
}
}
preOrderTraverse(T);
return 0;
}
int max(int x1, int x2)
{
if (x1 > x2)
{
return x1;
}
else
{
return x2;
}
}
int height(tree T)
{
if (T == NULL)
return -1;
else
{
return T->height;
}
}
position singleRotatewithLeft(position k2)
{
position k1 = k2->left;
k2->left = k1->right;
k1->right = k2;
k2->height = max(height(k2->left), height(k2->right)) + 1;
k1->height = max(height(k1->left), height(k2)) + 1;
return k1;
}
position singleRotatewithRight(position k2)
{
position k1 = k2->right;
k2->right = k1->left;
k1->left = k2;
k2->height = max(height(k2->right), height(k2->left)) + 1;
k1->height = max(height(k1->right), height(k2)) + 1;
return k1;
}
position doubleRotatewithLeft(position k3)
{
k3->left = singleRotatewithRight(k3->left);
return singleRotatewithLeft(k3);
}
position doubleRotatewithRight(position k3)
{
k3->right = singleRotatewithLeft(k3->right);
return singleRotatewithRight(k3);
}
tree insert(int x, tree T)
{
if (T == NULL)
{
T = malloc(sizeof(struct Node));
T->x = x;
T->height = 0;
T->left = T->right = NULL;
}
else
{
if (x < T->x)
{
T->left = insert(x, T->left);
if (height(T->left) - height(T->right) == 2)
{
if (x < T->left->x)
{
T = singleRotatewithLeft(T);
}
else
{
T = doubleRotatewithLeft(T);
}
}
}
if (x > T->x)
{
T->right = insert(x, T->right);
if (height(T->right) - height(T->left) == 2)
{
if (x > T->right->x)
{
T = singleRotatewithRight(T);
}
else
{
T = doubleRotatewithRight(T);
}
}
}
}
T->height = max(height(T->left), height(T->right)) + 1;
return T;
}
void preOrderTraverse(tree T)
{
if (T != NULL)
{
printf("%d,", T->x);
preOrderTraverse(T->left);
preOrderTraverse(T->right);
}
}