平衡二叉树.vc6.0

 #include<iostream.h>

typedef struct nd
{
 int bf;
 int n;
 struct nd *lch;
 struct nd *rch;
}btnode,*pbtnode;

class bltree
{
private:
 pbtnode root;
public:
 bltree()
 {
  root=0;
  int i;
  bool taller;
  cout<<"enter the node:0 is the endl:"<<endl;
  cin>>i;
  while(i)
  {
   Insert(root,i,taller);
   cin>>i;
  }
 }

 void l_rotate(pbtnode &rt)
 {
  pbtnode lc=rt->rch;
  rt->rch=lc->lch;
  lc->lch=rt;
  rt=lc;
 }

 void r_rotate(pbtnode &rt)
 {
  pbtnode rc=rt->lch;
  rt->lch=rc->rch;
  rc->rch=rt;
  rt=rc;
 }

 void leftbanlance(pbtnode &rt)
 {
  pbtnode lc=rt->lch;
  switch(lc->bf)
  {
  case 1:
   rt->bf=lc->bf=0;
   r_rotate(rt);
   break;
  case -1:
   pbtnode rc=lc->rch;
   switch(rc->bf)
   {
   case 1:
    rt->bf=-1;
    lc->bf=0;
    break;
   case -1:
    rt->bf=1;
    lc->bf=0;
    break;
   }
   rc->bf=0;
   l_rotate(lc);
   r_rotate(rt);
   break;
  }
 }

 void rightbanlance(pbtnode &rt)
 {
  pbtnode rc=rt->rch;
  switch(rc->bf)
  {
  case 1:
  {
   pbtnode lc=rc->lch;
   switch(lc->bf)
   {
   case 1:
    rt->bf=0;
    rc->bf=-1;
    break;
   case -1:
    rt->bf=1;
    rc->bf=0;
    break;
   }
   lc->bf=0;
   r_rotate(lc);
   l_rotate(rt);
   break;
  }
  case -1:
   rt->bf=rt->bf=0;
   l_rotate(rt);
   break;
  }
 }

 bool Insert(pbtnode &rt,int i,bool &taller)
 {
  if(!rt)
  {
   rt=new btnode;
   rt->n=i;
   rt->lch=rt->rch=0;
   rt->bf=0;
   taller=true;
  }
  else
  {
   if(rt->n==i)
   {
    taller=false;
    cout<<"it already in here!/n";
    return taller;
   }
   if(i<rt->n)
   {
    if(!Insert(rt->lch,i,taller))
     return 0;
    if(taller)
    {
     switch(rt->bf)
     {
     case 1:
      leftbanlance(rt);
      taller=false;
      break;
     case 0:
      rt->bf=-1;
      taller=true;
      break;
     case -1:
      rt->bf=0;
      taller=false;
      break;
     }
    }    
   }
   else
   {
    if(!(Insert(rt->rch,i,taller)))
     return 0;
    if(taller)
    {
     switch(rt->bf)
     {
     case 1:
      rt->bf=0;
      taller=false;
      break;
     case 0:
      rt->bf=-1;
      taller=true;
      break;
     case -1:
      rightbanlance(rt);
      taller=false;
      break;
     }
    }
   }
  }
  return 1;
 }

 void Inorder(pbtnode rt)
 {
  if(rt)
  {
   Inorder(rt->lch);
   cout<<rt->n<<"  ";
   Inorder(rt->rch);
  }
 }

 void print()
 {
  Inorder(root);
 }
};

void main()
{
 bltree bt;
 bt.print();

原文地址:https://www.cnblogs.com/thubier/p/11944288.html