平衡二叉树关键代码

struct AVLNode;
typedef struct AVLNode *PAVLNode;
struct AVLNode {
  KeyType key;
  int bf;
  PAVLNode llink,rlink;
};

typedef struct AVLNode *AVLTree;
typedef struct *PAVLTree;

int avlInsert(PAVLTree ptree, KeyType key)
{
  PAVLNode node_a, node_b, parent_a,p,q, node;
  int d;
  if(*ptree == NULL) {
    *ptree = createNode(key);
    return 1;
  }
  node_a = p = *ptree;
  parent_a = q =NULL;
  while(p!=NULL) {
    if(key == p->key) return 1;
    if(p->bf != 0) {
      parent_a = q;
      node_a = p;
    }
    q = p;
    if(key<p->key) p = p->llink;
    else p=p->rlink;
  }
  node = createNode(key);
  if(key<q->key) q->llink = node;
  else q->rlink = node;
  if(key<node_a->key) {
    p=node_b=node_a->llink;
    d = -1
  }
  else {
    p = node_b = node_a->rlink;d = 1;
  }
  while(p!=node){
    if(key<p->key){
      p->bf = -1;
      p=p->llink;
    }
    else {
      p->bf =1;
      p = p->rlink;
    }
  }
  if(node_a->bf == 0){
    node_a->bf = d;return 1;
  }
  if(node_a->bf == -d){
    node_a->bf = 0;return 1;
  }
  if(d == -1)
    if(node_b->bf == -1) node_b = lL(node_a, node_b);
    else node_b = lR(node_a,node_b);
  else 
    if(node_b->bf == 1) node_b = rR(node_a,node_b);
    else node_b = rL(node_a,node_b);
  if(parentp_a == NULL) *ptree = node_b;
  else{
    if(parent_a->llink == node_a) parent_a->llink = node_b;
    else parent_a->rlink = node_b;
  }
}

PAVLNode createNode (KeyType key){
  PAVLNode node = (PAVLNode)malloc(sizeof(AVLNode));
  if(node!=NULL) {
    node->key = key;
    node->bf = 0;
    node->llink = node->rlink = NULL;
  }
  return node;
}
PVLNode lL(PAVLNode a,PAVLNode b){
  a->bf = 0;
  a->llink = b->rlink;
  b->bf = 0;
  b->rlink = a;
  return b;
}

PAVLNode rR(PAVLNode a,PAVLNode b)
{
  a->bf = 0;
  a->rlink = b->llink;
  b->bf = 0;
  b->llink = a;
  return b;
}
PAVLNode lR(PAVLNode a,PAVLNode b)
{
  PAVLNode c = b->rlink;
  a->llink = c->rlink;
  b->rlink = c->llink;
  c->llink = b;
  c->rlink = a;
  switch(c->bf){
    case 0:a->bf = 0;b->bf = 0;break;
    case -1:a->bf = 1;b->bf=0;break;
    case 1:a->bf = 0;b->bf = -1;break;
  }
  c->bf = 0;return c;
}
PAVLNode rL(PAVLNode a,PAVLNode b)
{
  PAVLNode c = b->llink;
  a->rlink = c->llink;
  b->llink = c->rlink;
  c->llink = a;
  c->rlink = b;
  switch(c->bf){
    case 0:a->bf = 0;b->bf=0;break;
    case -1:a->bf=0;b->bf = -1;b->bf=1;break;
    case 1:a->bf = -1;b->bf = 0;break;
  }
  c->bf = 0;
  return c;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值