解题代码
#include<stdio.h>
#include<stdlib.h>
typedef struct tnode* ptn;
struct tnode {
int data;
ptn left, right;
int height;
};
ptn CreatTree(int K);
ptn Insert(ptn T, int K);
int GetHeight(ptn T);
int Max(int A, int B);
ptn Singleleftleftrotate(ptn A);
ptn Singlerightrightrotate(ptn A);
ptn Doubleleftrightrotate(ptn A);
ptn Doublerightleftrotate(ptn A);
int main()
{
int N;
int i, temp;
scanf("%d", &N);
scanf("%d", &temp);
ptn T = CreatTree(temp);
for (i = 1; i < N; i++) {
scanf("%d", &temp);
T = Insert(T, temp);
}
printf("%d", T->data);
return 0;
}
ptn CreatTree(int K) {
ptn T = (ptn)malloc(sizeof(struct tnode));
T->data = K;
T->height = 0;
T->left = T->right = NULL;
return T;
}
ptn Insert(ptn T,int K) {
if (!T) return CreatTree(K);
if (K < T->data) {
T->left = Insert(T->left, K);
if (GetHeight(T->left) - GetHeight(T->right) == 2) {
if (K < T->left->data) T = Singleleftleftrotate(T);
else if (K > T->left->data) T = Doubleleftrightrotate(T);
}
}
else if (K > T->data) {
T->right = Insert(T->right, K);
if (GetHeight(T->right) - GetHeight(T->left) == 2) {
if (K > T->right->data) T = Singlerightrightrotate(T);
else if (K < T->right->data) T = Doublerightleftrotate(T);
}
}
T->height = Max(GetHeight(T->left), GetHeight(T->right)) + 1;
return T;
}
int GetHeight(ptn T) {
if (!T) return -1;
else return T->height;
}
int Max(int A, int B) {
return A > B ? A : B;
}
ptn Singleleftleftrotate(ptn A) {
ptn B = A->left;
A->left = B->right;
B->right = A;
A->height = Max(GetHeight(A->left), GetHeight(A->right))+1;
B->height = Max(GetHeight(B->left), A->height)+1;
return B;
}
ptn Singlerightrightrotate(ptn A) {
ptn B = A->right;
A->right = B->left;
B->left = A;
A->height = Max(GetHeight(A->left), GetHeight(A->right)) + 1;
B->height = Max(GetHeight(B->right), A->height) + 1;
return B;
}
ptn Doubleleftrightrotate(ptn A) {
ptn B = A->left;
A->left = Singlerightrightrotate(B);
return Singleleftleftrotate(A);
}
ptn Doublerightleftrotate(ptn A) {
ptn B = A->right;
A->right = Singleleftleftrotate(B);
return Singlerightrightrotate(A);
}
测试结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/660cf0654ac994017d9489e79f8dd830.png)
问题整理
1.在判断语句中把不同的类型做比较导致错误。
2.忘记在LL和RR中更新height的值。