平衡二叉树是一种二叉排序树,其中每一个节点的左子树和右子树的高度差至多等于1.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
typedef struct _node
{
int data;
int high;
struct _node *left;
struct _node *right;
}node,*pnode;
//构建二叉树
pnode construct_node(int data)
{
pnode temp = (pnode)malloc(sizeof(node));
memset(temp,0,sizeof(node));
temp->high = 0;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
//中序遍历
void inorder_travel(pnode root)
{
if(root == NULL)
return ;
pnode temp = root;
if(temp != NULL)
{
if(temp->left != NULL)
{
inorder_travel(temp->left);
}
printf("%d(%d) \t",temp->data,temp->high);
if(temp->right != NULL)
{
inorder_travel(temp->right);
}
}
}
//左右子树深度
int hight(pnode root)
{
if(root == NULL)
return -1;
else
return root->high;
}
int max(int a,int b)
{
return (a > b ? a:b);
}
//单左旋
pnode single_rotate_left(pnode root)
{
pnode tmp = root ->left;
root->left = tmp->right;
tmp->right = root;
//旋转后更新高度
root->high = max(hight(root->left),hight(root->right)) +1;
tmp->high = max(hight(tmp->left),hight(tmp->right))+1;
return tmp;
}
//单右旋
pnode single_rotate_right(pnode root)
{
pnode tmp = root->right;
root->right= tmp->left;
tmp->left = root;
root->high = max(hight(root->left),hight(root->right)) +1;
tmp->high = max(hight(tmp->left),hight(tmp->right))+1;
return tmp;
}
//双旋,先右旋,再左旋
pnode double_rotate_left(pnode root)
{
root->left = single_rotate_right(root->left);
return single_rotate_left(root);
}
//双旋,先左旋,再右旋
pnode double_rotate_right(pnode root)
{
root->right = single_rotate_left(root->right);
return single_rotate_right(root);
}
//添加节点
pnode add_node(pnode root,pnode newnode)
{
if(root == NULL)
{
return newnode;
}
pnode temp = root;
if(temp->data > newnode->data)//left
{
temp->left = add_node(temp->left,newnode);
//平衡因子BF超过2 需要旋转
if(hight(temp->left) - hight(temp->right) >= 2)
{
if(temp->left->data > newnode->data)//LL
{
temp = single_rotate_left(temp);
}
else //LR
{
temp = double_rotate_left(temp);
}
}
//
}
else if(temp->data < newnode->data)
{
temp->right = add_node(temp->right,newnode);
if(hight(temp->right) - hight(temp->left) >= 2)
{
if(temp->right->data < newnode->data)//RR
{
temp = single_rotate_right(temp);
}
else//RL
{
temp = double_rotate_right(temp);
}
}
}
//更新高度
temp->high = max(hight(temp->left),hight(temp->right))+1;
return temp;
}
int main(int argc,char *argv[])
{
if(argc != 2)
{
printf("");
exit(EXIT_FAILURE);
}
int num = atoi(argv[1]);
srand(time(NULL));
int i;
//root
pnode root = NULL;
for(i = 0;i< num;i++)
{
pnode temp = construct_node(rand()%500);
root = add_node(root,temp);
}
inorder_travel(root);
printf("\n");
return 0;
}