BST二叉查找树 查找 插入 建立 删除

struct node {

    int data;

    node* lchild;

    node* rchild;

    node() {}

    node(int a):data(a),lchild(NULL),rchild(NULL) {

    }

};

void search(node* root,int x) {                   //查找

    if(root==NULL) {

        cout<<"Fail"<<endl;

        return ;

    }

    if(root->data==x) {

        cout<<root->data<<endl;

    else if(x<root->data) {

        search(root->lchild,x);

    else {

        search(root->rchild,x);

    }

}

void Insert(node* & root,int x) {          //插入

    if(root==NULL) {

        node* n=new node(x);

        return ;

    }

    if(x==root->data) {

        return ;

    }

    if(x<root->lchild) {

        Insert(root->lchild,x);

    else {

        Insert(root->rchild,x);

    }

}

node* create(int* a,int n) {                //建立

    node* root=NULL;                      //注意空根结点的建立

    for(int i=0; i<n; i++) {

        Insert(root,a[i]);

    }

    return root;

}

node* Max(node* root) {                    //左子树最大值,从左子树根结点

    while(root-rchild!=NULL) {

        Max(root->rchild);

    }

    return root;

}

node* Min(node* root) {                    //右子树最大值,从右子树根结点

    while(root->lchild!=NULL) {

        Min(root->lchild);

    }

    return root;

}

void del(node* root,int x) {                       //删除

    if(root==NULL) return ;

    if(root->data==x) {

        if(root->lchild==NULL&&root->rchild==NULL) {

            root=NULL;

        else if(root->lchild!=NULL) {

            node* pre=Max(root->lchild);

            root->data=pre->data;

            del(root->lchild,pre->data);

        else {

            node* next=Min(root->rchild);

            root->data=next->data;

            del(root->rchild,next->data);

        }

    else if(x>root->data) {

        del(root->rchild,x);

    else {

        del(root->lchild,x);

    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值