跳到正文

个人记录

搜索二叉树

wuzhenduo约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年3月23日
收录
2026年8月24日
更新
2026年11月10日
篇幅
约 3 分钟

版本

  1. v1当前

搜索二叉树

导入

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

定义搜索二叉树

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

查找

C++
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;
	}
}

插入

C++
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;
}

删除

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

输出

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

输入

C++
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);
		}
	}
原文