搜索二叉树

· · 个人记录

搜索二叉树

导入

搜索二叉树是一种基于二分的一种数据结构,其特点 是左定点一定小于父节点,是右定点一定大于父节点 因为这个特点就可以实现数据可以查找

定义搜索二叉树

struct node{
    int fu,zs,zuo,you;//zs:自己的值 zuo:左顶点的下标 you:右顶点的下标 
    long long sum=0;
}h[1000];

查找

int chazhao(int x,int z){
    if(h[z].zs==x&&h[z].sum>=1)return z;
    else{
        if(h[z].zs<x){
            if(h[z].you!=-1){
                return chazhao(x,h[z].you);
            }
            else
            {
                return z;
            }
        }
        if(h[z].zs>x){
            if(h[z].zuo!=-1){
                return chazhao(x,h[z].zuo);
            }
            else
            {
                return z;
            }
        }
    }
    if(h[z].zuo==-1&&h[z].you==-1)
    {
        return z;
    }
}

插入

int charu(int x){
    int z=chazhao(x,1);
    if(h[z].zs==x) h[z].sum++;
    else
    {
        if(h[z].zs<x)
        {
            h[ans].fu=z;
            h[z].you=ans;
            h[ans].zs=x;
            h[ans].zuo=h[ans].you=-1;
            h[ans].sum=1;
        }
        else
        {
            h[ans].fu=z;
            h[z].zuo=ans;
            h[ans].zs=x;
            h[ans].zuo=h[ans].you=-1;
            h[ans].sum=1;
        }
    }
    return 0;
}

删除

int shanchu(int x)
{
    int z=chazhao(x,1);
    h[z].sum--;
    return 0;
}

输出

for(int i=1;i<=ans;i++)if(h[i].sum>=1)cout<<h[i].zs<<" ";

输入

for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        if(ans==0)
        {
            ans++;
            h[1].zs=x;
            h[1].fu=-1;
            h[1].zuo=h[1].you=-1;
            h[1].sum=1;
        }
        else
        {
            ans++;
            int z1=charu(x);
        }
    }