平衡二叉树建立

平衡二叉树

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值