二叉排序树的简单实现

   今天实现下二叉排序树的算法,为学习avl,rbt,做好准备,那我们就开始吧,。

#include "iostream"
using namespace std;
typedef struct _BitNode
{
    int data;
    struct _BitNode *lchild,*rchild;
}BitNode,*BiTree;
//搜索元素,参数:(0: 根节点,1: 查找的元素,2: 找到目标元素的前一个节点指针,初始值为0
// 3:找到元素的指针)
 bool SearchBST(BiTree T,int key,BiTree pre,BiTree&n)
 {
     if(!T)
     {
         n=pre;
         return false;
     }
     else if(key==T->data)
     {
         n=T;
         return true;
     }
     if(key<T->data)
         SearchBST(T->lchild,key,T,n) ;
     else
     {
         SearchBST(T->rchild,key,T,n);
     }
 }
 //插入元素
 bool InsetBST(BiTree &T,int k)
 {
     BitNode* p;
     if(!SearchBST(T,k,NULL,p))
     {   BitNode * temp=new BitNode;
         temp->data=k;
         temp->lchild=temp->rchild=NULL;
         if(!p)
         {
           T=temp; 
         }
         else
         {
             if(k<p->data)
                 p->lchild=temp;
             else
             {
                 p->rchild=temp;
             }
         }
         return 0;
     }
     else 
     {
         return false;
     }
 }
 //中序遍历并输出元素
 void InorderReverse(BiTree T)
 {
     if(T)
     {
         InorderReverse(T->lchild);
         cout<<T->data<<endl;
         InorderReverse(T->rchild);
     }
 }
 //从树种删除元素,分三种情况1,删除的元素只有右子树,2 只有左子树,3 有左右子树
 void Delete(BiTree&T)
 {
     BitNode*s,*p;
     if(T->rchild==NULL)
     {   s=T;
        
         T=T->lchild;
          free(s);
     }
     else if(T->lchild==NULL)
     {
         s=T;
        
         T=T->rchild;
          free(s);
     }
     else
     {
         p=T;
         s=T->lchild;
         while (s->rchild)
         {
             p=s;
             s=s->rchild;
         }
         T->data=s->data;
         if(p!=T)
         {
             p->rchild=s->lchild;
         }
         else 
             p->lchild=s->lchild;
         free(s);
     }
 }
 bool DeleElement(BiTree&T,int key)
 {
    
         if(!T)
          {
              return 0;
          }
         if(T->data==key)
         {
             Delete(T);
             return 1;
         }
         if(key<T->data)
            DeleElement(T->lchild,key);
         else 
            DeleElement(T->rchild,key);
    

 }
 
int main()
{
    BiTree tree=NULL;
    int a[]={62,88,58,47,35,73,51,99,37,93};
    for(int i=0;i<10;i++)
        InsetBST(tree,a[i]);
    InorderReverse(tree);
    cout<<"             "<<endl<<endl;
    DeleElement(tree,62);
    InorderReverse(tree);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值