基于二叉顺序树的折半查找

思路:先将无序数字建立二叉顺序树,将二叉顺序树中序遍历的结果储存起来,然后对该结果进行折半查找,查找的到就直接打印,查找不到就插入再次进行查找

整体代码:

#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;
	}
}

实现结果:

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

How to Learn

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

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

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

打赏作者

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

抵扣说明:

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

余额充值