我正在为AVL树正确旋转。但是它给出了运行时错误。目前我忽略了AVL树的高度部分。我稍后会处理它。但是只要在5处应用右旋转就会产生问题。请救命。 我使用的AVL树是:
9(Root)
5(Left Child) 13(Right Child)
3 7 11 17
2
1
C代码:
#include <stdio.h>
#include <malloc.h>
struct AVLTree
{
int data;
struct AVLTree *left;
struct AVLTree *right;
};
struct AVLTree *RightRotate(struct AVLTree *rootop)
{
struct AVLTree *A = rootop->left;
rootop->left = A->right;
A->right = rootop;
return A;
}
int main()
{
struct AVLTree * root = (struct AVLTree *)malloc(sizeof(struct AVLTree));
root-> data = 9;
struct AVLTree * l = (struct AVLTree *)malloc(sizeof(struct AVLTree));
l -> data = 5;
struct AVLTree * ll = (struct AVLTree *)malloc(sizeof(struct AVLTree));
ll -> data = 3;
ll -> left = ll -> right = NULL;
struct AVLTree * lll = (struct AVLTree *)malloc(sizeof(struct AVLTree));
lll -> data = 2;
lll -> left = lll -> right = NULL;
ll->left = lll;
struct AVLTree * llll = (struct AVLTree *)malloc(sizeof(struct AVLTree));
llll -> data = 1;
llll -> left = llll -> right = NULL;
lll->left = llll;
struct AVLTree * lr = (struct AVLTree *)malloc(sizeof(struct AVLTree));
lr -> data = 7;
lr -> left = lr -> right = NULL;
l -> left = ll;
l -> right = lr;
struct AVLTree * r = (struct AVLTree *)malloc(sizeof(struct AVLTree));
r -> data = 13;
struct AVLTree * rl = (struct AVLTree *)malloc(sizeof(struct AVLTree));
rl -> data = 11;
rl -> left = rl -> right = NULL;
struct AVLTree * rr = (struct AVLTree *)malloc(sizeof(struct AVLTree));
rr -> data = 17;
rr -> left = rr -> right = NULL;
r -> left = rl;
r -> right = rr;
root -> left = l;
root -> right = r;
RightRotate(l);
printf("Root is %d\n",root->data);
printf("Left is %d\n",l->data);
printf("Left left is %d\n",l->left->data);
printf("Left right is %d\n",l->right->data);
printf("Left Ka Left is %d\n",ll->data);
printf("LL left is %d\n",ll->left->data);
printf("Left Ka Left Ka Left is %d\n",lll->data);
printf("LLL left is %d\n",lll->left->data);
return 0;
}
答案 0 :(得分:0)
我认为您应该写一些类似l = RightRotate(l)
的内容,因为您的RightRotate
函数会返回struct AVLTree *
。