查找的基本操作与应用
算法要求:
- 掌握查找的不同方法,并能用高级语言实现查找算法;
- 熟练掌握二叉排序树的构造和查找方法
- 了解静态查找表及哈希表查找方法。
#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;
}