2021-06-15

查找的基本操作与应用

算法要求:

  1. 掌握查找的不同方法,并能用高级语言实现查找算法;
  2. 熟练掌握二叉排序树的构造和查找方法
  3. 了解静态查找表及哈希表查找方法。
#include <iostream>
using namespace std;
typedef struct BTNode
{
	int key;
	struct BTNode *lchild;
	struct BTNode *rchild;
}BTNode; 
//二叉排序树的关键字查找
BTNode* BSTSearch(BTNode* bt,int key)
{
	if(bt== NULL)
		return NULL;
	if(bt->key== key)
		return bt;
	else if(bt->key> key)
		return BSTSearch(bt->lchild,key);
	else
		return BSTSearch(bt->rchild, key);	
		
}
//二叉排序树的结点的插入小
int BSTInsert(BTNode *&bt, int key)
{
	if(bt== NULL)
	{
		//当前为空指针说明找到了插入位置,创建新结点在此插入
		bt=(BTNode*)malloc(sizeof(BTNode));
		bt->lchild=bt->rchild=NULL;
		bt->key= key;
		return 1;
	}
	else
	{
		if(bt->key==key)
			return 0;
		else if(bt->key> key)
			return BSTInsert (bt->lchild, key);
		else
			return BSTInsert (bt->rchild, key);
	}
}

void createBST(BTNode *&bt,int key[],int n)
{
	int i;
	bt=NULL;
	for(i=0;i<n;++i)
	{
		BSTInsert(bt, key[i]);
	}
}

int main()
{
	BTNode *bt;
	int key[]={3,4,5,7,8,9,10};
	int n = 7;
	createBST(bt,key,n);
	BTNode *p;
	p=BSTSearch(bt,6);
	if(p==NULL)
		cout<<"没有找到"<<endl;
	else
		cout<<"找到了"<<p->key<<endl;
	int res =BSTInsert(bt,6);
	cout<<res<<endl;
	p = BSTSearch(bt,6);
	if(p==NULL)
		cout<<"没有找到"<<endl;
	else
		cout<<"找到了"<<p->key<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CJ_小前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值