平衡二叉树
struct node {
int date;
node * left;
node * right;
};
strutc node * tree;
## 算树高
int getheight(tree root)
{
int rh,lh,maxh;
if(root==NULL)
{return 0;}
else
{
rh=getheight(root->right);
hl=getheight(root->left);
maxh=rh>lh?rh:lh;
return maxh+1;
}
}
## 左单旋(顺时针)
tree ll(tree root)
{
tree b=root->left;
root->left=b->right;
b->right=root;
return b;
}
## 右单旋(逆时针)
tree rr(tree root)
{
tree b=root->right;
root->right=b->left;
b->left->root;
return b;
}
## 左右双旋
tree lr(tree root)
{
root->left=rr(root->left);
return ll(root);
}
## 右左双旋
tree rl(tree root)
{
root->right=ll(root->right);
return rr(root);
}
## 插入(建树)
tree insert(tree root,int x)
{
if(root==NULL)
{
root=new node;
root->date=x;
root->left=root->right=NULL;
return root;
}
else
{
if(x< root->date)
{
insert(root->left,x);
if(getheight(root->left)-getheight(root->right)==2)
{
if(xleft->date)
{
root=ll(root);
}
else root=lr(root);
}
}
else if(x>root->date)
{
insert(root->right,x);
if(getheight(root->right)-getheight(root->left)==2)
{
if(x>root->right->date)
{
root=rr(root);
}
else root=rl(root);
}
}
}
return root;
}