#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef int SBTType;
typedef struct SBBTree {
SBTType data;
struct SBBTree* lchild, * rchild;
int hight;
}BTNode, *BTree;
int gethight(BTree root);
int whomax(int a, int b);
void LL(BTree* root);
void RR(BTree* root);
void avlInsert(BTNode** t,int x);
int gethight(BTree root ) {
if (root) {
return root->hight;
}
else {
return 0;
}
}
int whomax(int a, int b) {
return a > b ? a : b;
}
void LL(BTree* root) {
BTNode* mid= (*root)->lchild;
(*root)->lchild = mid->rchild;
mid->rchild = (*root);
(*root) = mid;
(*root)->hight = whomax(gethight((*root)->lchild), gethight((*root)->rchild)) + 1;
mid->hight = whomax(gethight(mid->lchild), gethight(mid->rchild)) + 1;
}
void RR(BTree* root) {
BTNode* mid = (*root)->rchild;
(*root)->rchild = mid->lchild;
mid->lchild = (*root);
(*root) = mid;
(*root)->hight = whomax(gethight((*root)->lchild), gethight((*root)->rchild)) + 1;
mid->hight = whomax(gethight(mid->lchild), gethight(mid->rchild)) + 1;
}
void avlInsert(BTNode** t, int x) {
if ((*t) == NULL) {
(*t) = (BTNode*)malloc(sizeof(BTNode));
if (!(*t)) {
printf("fail");
}
else {
(*t)->data = x;
(*t)->lchild = NULL;
(*t)->rchild = NULL;
(*t)->hight = 0;
}
}
else if ((*t)->data > x) {
avlInsert(&((*t)->lchild), x);
int Lh = gethight((*t)->lchild);
int Rh = gethight((*t)->rchild);
if (Lh - Rh == 2) {
if (x < ((*t)->lchild)->data) {
LL(t);
}
else {
RR(&((*t)->lchild));
LL(t);
}
}
}
else if ((*t)->data < x) {
avlInsert(&((*t)->rchild), x);
int Lh = gethight((*t)->lchild);
int Rh = gethight((*t)->rchild);
if (Lh - Rh == 2) {
if (x > ((*t)->rchild)->data) {
RR(t);
}
else {
LL(&((*t)->rchild));
RR(t);
}
}
}
(*t)->hight = whomax(gethight((*t)->lchild), gethight((*t)->rchild)) + 1;
}
void preOrder(BTNode* T) {
if (T) {
printf("%d ", T->data);
preOrder(T->lchild);
preOrder(T->rchild);
}
}
int main ()
{
BTree t;
int num[5] = { 1,8,6,7,10 };
for (int i = 0; i < 5; i++) {
avlInsert(&t, num[i]);
}
preOrder(t);
return 0;
}
