思路:先将无序数字建立二叉顺序树,将二叉顺序树中序遍历的结果储存起来,然后对该结果进行折半查找,查找的到就直接打印,查找不到就插入再次进行查找
整体代码:
#include<iostream>
#include<queue>
using namespace std;
int i,j,k,e,n;
queue<int> dui;
typedef struct {
int key;
int otherwise;
} elemtype;
typedef struct bstnode {
elemtype data;
int length;
struct bstnode *lchild,*rchild;
} bstnode,*bstree;
typedef struct{
int a[100];
int TableLen;
}SSTable;
SSTable table;
void insertbstnode(bstree &T,int e) {
if(!T) {
bstree s;
s=new bstnode;
s->data.key=e;
s->lchild=s->rchild=NULL;
T=s; //将插入的点链接到已找到的插入位置
} else if(e<T->data.key) //小于当前结点的话,按照其左孩子寻找
insertbstnode(T->lchild,e);
else if(e>T->data.key) //大于当前结点的话,按照其右孩子寻找
insertbstnode(T->rchild,e);
}
void creatbstnode(bstree &T) {
T=NULL; //注意这个地方T要为空 ,建立根节点
for(i=0; i<n; i++) {
cin>>e;
insertbstnode(T,e);
}
}
void printfbstree(bstree T,queue<int> &dui) {
if(T) {
printfbstree(T->lchild,dui);
dui.push(T->data.key);
printfbstree(T->rchild,dui);
}
}
void cleanqueue(queue<int> &dui){
while(!dui.empty()){
dui.pop();
}
}
void changetree(queue<int> dui,SSTable &table)
{
for(int i=0;i<table.TableLen;i++){
table.a[i] = dui.front();
dui.pop();
}
}
int Binary_Search(SSTable L, int key)
{
int low=0, high=L.TableLen-1, mid;
while(low<=high)
{
mid=(low+high)/2;
if(L.a[mid]==key)
return mid; //查找成功则返回所在位置
else if(L.a[mid]>key)
high=mid-1; //从前半部分继续查找
else
low=mid+1; //从后半部分继续查找
}
return -1; //查找失败,返回-1
}
int main() {
bstree T;
int number;
printf("请输入数的数量:\n");
cin>>n;
table.TableLen = n;
printf("请输入数字:\n");
creatbstnode(T);
printfbstree(T,dui);
changetree(dui,table);
cout<<"请输入你想查询的数字"<<endl;
cin>>number;
if(Binary_Search(table,number)==-1){
cout<<"查询数字不存在,现在已经插入,它的位置是:";
table.TableLen ++;
cleanqueue(dui);
insertbstnode(T,number);
printfbstree(T,dui);
changetree(dui,table);
cout<<Binary_Search(table,number)<<endl;
}
else{
cout<<"你查询的数字在:";
cout<<Binary_Search(table,number)<<endl;
}
}
实现结果: