#include <stdio.h>
#include <stdlib.h>
typedef struct treenode
{
int data;
int height;
struct treenode *left;
struct treenode *right;
} TreeNode, *AVL;
int Max(int a, int b)
{
return (a > b) ? a : b;
}
int Height(AVL root)
{
return (root == NULL) ? 0 : root->height;
}
void PreOrder(AVL root)
{
if (root)
{
printf("%d,", root->data);
PreOrder(root->left);
PreOrder(root->right);
}
}
AVL right_right_rotation(AVL k3)
{
AVL k1 = k3->right;
k3->right = k1->left;
k1->left = k3;
k3->height = Max(Height(k3->left), Height(k3->right)) + 1;
k1->height = Max(k3->height, Height(k1->right)) + 1;
return k1;
}
AVL left_left_rotation(AVL k1)
{
AVL k3 = k1->left;
k1->left = k3->right;
k3->right = k1;
k1->height = Max(Height(k1->left), Height(k1->right)) + 1;
k3->height = Max(k1->height, Height(k3->left)) + 1;
return k3;
}
AVL left_right_rotation(AVL k3)
{
k3->left = right_right_rotation(k3->left);
return left_left_rotation(k3);
}
AVL right_left_rotation(AVL k3)
{
k3->right = left_left_rotation(k3->right);
return right_right_rotation(k3);
}
AVL create(AVL root, int data)
{
if (root == NULL)
{
AVL p = (AVL)malloc(sizeof(TreeNode));
p->left = p->right = NULL;
p->data = data;
p->height = 0;
root = p;
}
if (data > root->data)
{
root->right = create(root->right, data);
if (Height(root->right) - Height(root->left) == 2) //需要调整
{
if (data > root->right->data)
root = right_right_rotation(root);
else if (data < root->right->data)
root = right_left_rotation(root);
}
}
else if (data < root->data)
{
root->left = create(root->left, data);
if (Height(root->left) - Height(root->right) == 2)
{
if (data > root->left->data)
root = left_right_rotation(root);
else if (data < root->left->data)
root = left_left_rotation(root);
}
}
root->height = Max(Height(root->left), Height(root->right)) + 1;
return root;
}
int main()
{
char a[31];
scanf("%s", a);
int i = 0, run = 0;
int b[31];
int sum = 0;
while (a[i])
{
if (a[i] != ',')
{
sum = sum * 10 + a[i] - '0';
}
else if (a[i] == ',')
{
b[run++] = sum;
sum = 0;
}
i++;
}
AVL root = NULL;
i = 0;
while (i < run)
{
root = create(root, b[i]);
//printf("%d ",b[i]);
i++;
}
PreOrder(root);
return 0;
}
数据结构第二次作业第二题(AVL树)
最新推荐文章于 2021-08-28 16:21:58 发布