树
1.二叉树
struct TBNode
{
int data;
TBNode *lchild , *rchild;
}
TBNode *root=NULL;
//创立新的节点;
TBNode *newNode(int v)
{
TBNode* Node=(TBNode*)malloc(sizeof(TBNode));
Node->datat=v;
Node->lchild=Node->rchild=NULL;
return Node;
}
//插入
void insert(TBNode* &root,int x)
{
if(root==NULL)
{
root=newNode(x);
return;
}
if(由二叉树的性质,x应该插在左子树)
{
insert(root->lchild,x);
}else
{
insert(root->rchild,x);
}
}
二叉树的创立
TBNode *create(int data[],int n)
{
TBNode* root=NULL;
for(int i=0;i<n;i++)
{
insert(root,datat[i]);
}
return root;
}
2.平衡二叉树
struct node
{
int v,height;
node *lchild,*rchild;
}
node* newnode(int v)
{
node* Node=new node;
Node->v=v;
Node->height=1;//结点高度初始为一;
Node->lchild=Node->rchild=NULL;
return Node;
}
int getheight(node* root)
{
if(root==NULL)return 0;
return root->height;
}
//计算平衡因子
int getBalanceFactor(node* root)
{
return getHeight(root->lchild)-getHeight(root->rchild);
}
//更新高度
void updateHeight(node* root)
{
root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}
基本操作:
1.查找操作跟搜索二叉树一样;
2.插入操作:
作者:Coding-Naga
链接:http://blog.csdn.net/lemon_tree12138/article/details/50393548
我们对于结点平衡的定义:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
插入会引起平衡树左右高度差大于1,所以要进行优化;
失衡有如下四种情况;
(1)在一个节点的左子树的左子树上插入一个新节点。即LL。在这种情况下,我们可以通过将节点右旋使其平衡。如图-2所示;

图-2 LL单右旋操作
(2)在一个节点的右子树的右子树上插入一个新节点。即RR。在这种情况下,我们可以通过将节点左旋使其平衡。如图-3所示;

图-3 RR单左旋操作
(3)在一个节点的左子树的右子树上插入一个新节点。即LR。在这种情况下,我们不能直接通过将节点左旋或右来使其平衡了。这里需要两步来完成,先让树中高度较低的进行一次左旋,这个时候就变成了LL了。再进行一次单右旋操作即可。如图-4所示;

图-4 LR先左旋再右旋操作
(4)在一个节点的右子树的左子树上插入一个新节点。即RL。在这种情况下,我们不能直接通过将节点左旋或右来使其平衡了。这里需要两步来完成,先让树中高度较低的进行一次右旋,这个时候就变成了RR了。再进行一次单左旋操作即可。如图-5所示;

图-5 RL先右旋再左旋操作
//左旋(left rotation)记住 &root;
void L(node* &root)
{
node*temp=root->rchild;
root->rchild=temp->lchild;//步骤1
temp->lchild=root;//步骤2;
updateHeight(root);//更新结点A的高度
updateHeight(temp);//更新结点B的高度
root=temp;//步骤3;
}
//类似右旋
void R(node* &root)
{
node*temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
updateHeight(root);
updateHeight(temp);
root=temp;
}
接下来可以写AVL的插入;
void insert(node* &root,int v)
{
if(root==NULL)
{
root=newNode(v);
return;
}
if(v<root->v)
{
insert(root->lchild,v);
updateHeight(root);
if(getBalanceFactor(root)==2)
{
if(getBalanceFactor(root->lchild)==1)
{
R(root);//插在左子树的左子树,LL,使用右旋;
}else if(getBalanceFactor(root->lchild)==-1)//LR
{
L(root->lchild);
R(root);
}
}
}else
{
insert(root->rchild,v);
updateHeight(root);
if(getBalanceFactor(root)==-2)
{
if(getBalanceFactor(root->rchild)==-1)
{
L(root);//插在右子树的右子树,RR,使用左旋;
}else if(getBalanceFactor(root->rchild)==1)//RL
{
R(root->rchild);
L(root);
}
}
}
3.AVL的建立
node* create(int data[ ],int n)
{
node *root=NULL;
for(int i=0;i<n;i++)
{
insert(root,data[i]);
}
return root;
}

浙公网安备 33010602011771号