二叉搜索树的实现(insert、find、remove)

白书研究,beginning.......

有不懂的地方欢迎留言。。。


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <map>
#include <sstream>
#include <queue>
#include <stack>
#define INF 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a));
#define For(a,b) for(int i = a;i<b;i++)
#define LL long long
#define MAX_N 100010
using namespace std;
struct node
{
    int val;
    node *lc,*rc;
};
node *insert(node *p,int x)
{
    if(p == nullptr)
    {
        node *q = new node;
        q->val = x;
        q->lc = q->rc = nullptr;
        //cout<<"On the way."<<endl;
        return q;
    }
    else
    {
        if(x < p->val) p->lc = insert(p->lc,x);
        else  p->rc = insert(p->rc,x);
        return p;
    }
}
bool find(node *p,int x)
{
    if(p == nullptr) return false;
    else if(p->val == x) return true;
    else if(p->val < x) return find(p->rc,x);
    else if(p->val > x) return find(p->lc,x);
}
node *remove(node *p,int x)
{
    if(p == nullptr) return p;
    else if(p->val > x) p->lc = remove(p->lc,x);
    else if(p->val < x) p->rc = remove(p->rc,x);
    else if(p->lc == nullptr)
    {
        node *q = p->rc;
        delete p;
        return q;
    }
    else if(p->lc->rc == nullptr)
    {
        node *q = p->lc;
        q->rc = p->rc;
        delete p;
        return q;
    }
    else
    {
        node *q;
        for(q = p->lc; q->rc->rc != nullptr; q = q->rc) ;
        node *t = q->rc;
        q->rc = t->lc;
        t->lc = p->lc;
        t->rc = p->rc;
        delete p;
        return t;
    }
    return p;
}
int main()
{
    node *head = nullptr;
    int d[10] = {10,2,11,35,6,9,24};
    for(int i = 0; i<7; i++)
    {
        head = insert(head,d[i]);
    }
    bool flag = find(head,6);
    if(flag) cout<<"In the binary tree."<<endl;
    else cout<<"Don`t in the binary tree."<<endl;
    remove(head,6);
    bool flag1 = find(head,9);
    if(flag1) cout<<"In the binary tree."<<endl;
    else cout<<"Don`t in the binary tree."<<endl;
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值