BST树(双重指针版,未完)

                                 这个双重指针还是不太明白。


 不用引用操作符的话,就只能用双重指针来操作了。

然后要记住:在main函数外要修改谁就要传谁的地址。

//在传参的函数中,想要修改谁,就要传谁的地址。
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct node
{
    int data;
    //二重指针用来一重指针的值。
    node **l;
    node **r;

    node *ll;
    node *rr;
}BST;
bool Insert(BST **bt,int key)
{
    if(*bt==NULL)
    {
        *bt=(BST*)malloc(sizeof(BST));
        (*bt)->data=key;
        (*bt)->ll=NULL;
        (*bt)->l=&((*bt)->ll);
        (*bt)->rr=NULL;
        (*bt)->r=&((*bt)->rr);
        return true;
    }
    else if(key==(*bt)->data) return false;
    else if(key<(*bt)->data) return Insert((*bt)->l,key);
    else  return Insert((*bt)->r,key);
}
void Print(BST *root)
{
    if(root!=NULL)
    {
        Print(*(root->r));
        cout<<root->data<<" ";
        Print(*(root->l));
    }
}

BST *BSearch(BST* bt,int key)
{
    if(bt==NULL||bt->data==key) return bt;
    else if(bt->data>key) return BSearch(bt->ll,key);
    else                  return BSearch(bt->rr,key);
}

void DeleteP2(BST* p,BST **r)//当前结点具有左子树和右子树
{
    BST *q;
    if((*r)->rr!=NULL)
    {
        DeleteP2(p,(*r)->r);
    }
    else
    {
        p->data=(*r)->data;
        q=*r;
        *r=(*r)->ll;
        free(q);
    }
}

void DeleteP(BST** p)
{
    BST *q;
    if((*p)->rr==NULL)//右子树为空
    {
        q=*p;
        (*p)=(*p)->ll;
        free(q);
    }
    else if((*p)->ll==NULL)//左子树为空
    {
        q=*p;
        (*p)=(*p)->rr;
        free(q);
    }
    else DeleteP2(*p,(*p)->l);//当前结点具有左子树和右子树
}


bool DeleteBst(BST** p,int key)//删除操作的起始函数
{
    if(*p==NULL) return false;
    else
    {
        if(key==(*p)->data)
        {
            DeleteP(p);
            return true;
        }
        else if(key<(*p)->data) return DeleteBst((*p)->l,key);
        else return  DeleteBst((*p)->r,key);
    }
}

int main()
{
    BST *root=NULL;
    BST **tmp1=&root;
    int a[]={5,1,2,3,4,6,7,8,10,0};
    int len=sizeof(a)/(sizeof(a[0]));

    //插入
    for(int i=0;i<len;i++)
    {
        Insert(tmp1,a[i]);//插入操作
    }

    Print(root);//从大到小输出树

    //查找某个值
     BST*b= BSearch(root,5);
    if(b==NULL)  cout<<"未找到\n";
    else cout<<b->data<<"##\n";

    //删除某个值
    DeleteBst(tmp1,6);
    Print(root);
    cout<<endl;
    for(int i=1;i<=5;i++)
        DeleteBst(tmp1,i);

    Print(root); cout<<endl;

    return 0;
}

课设的铺垫就结束了。。做课设的话,就只需要改下功能,然后能让函数互相调用就可以了。


双重指针把我整懵了,尤其是后面的删除结点功能,已经不知道要怎么改了,可能主要还是不理解吧。

指针确实值得好好学下。

最后,c++的引用真香!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值