实现二叉查找树进行数据查找

//实现二叉查找树进行数据查找
#include<iostream>
#include<malloc.h>
typedef struct BiNode{
    int data;
    struct BiNode *lchild, *rchild;
}BiNode;
typedef BiNode* BiTree;
using namespace std;
void InsertBST(BiTree *bst, int key)
/*若在二叉排序树中不存在关键字等于key的元素,插入该元素*/
{ 
	BiTree s;
	if (*bst == NULL)/*递归结束条件*/
	{
		s=(BiTree)malloc(sizeof(BiNode));/*申请新的结点s*/
		s->data=key;
		s->lchild=NULL; 
		s->rchild=NULL;
		*bst=s;
	}
	else 
		if (key < (*bst)->data)
			InsertBST(&((*bst)->lchild), key);/*将s插入左子树*/
		else 
			if (key > (*bst)->data)
				InsertBST(&((*bst)->rchild), key); /*将s插入右子树*/
}
BiTree SearchBST(BiTree bst,int key)
/*在根指针bst所指二叉排序树中,递归查找某关键字等于key的元素,
若查找成功,返回指向该元素结点指针,否则返回空指针*/
{ 
	if (!bst) 
		return NULL;
	else 
		if (bst->data == key)
			return bst;/*查找成功*/
		else
			if (bst->data > key)
				return SearchBST(bst->lchild, key);/*在左子树继续查找*/
			else 
				return SearchBST(bst->rchild, key);/*在右子树继续查找*/
}
void InOrder(BiTree root) 
/*中序遍历二叉树, root为指向二叉树根结点的指针*/
{
	if (root!=NULL)
	{
		InOrder(root->lchild);  /*中序遍历左子树*/
		cout<<root->data<<" ";  /*输出结点*/
		InOrder(root->rchild);  /*中序遍历右子树*/
	}
}
int main()
{
	cout<<"输入数据个数:\n";
    int n, data;
    cin>>n;
    BiTree T = NULL;
    cout<<"请输入"<<n<<"个数:\n";
    while(n--) 
	{
        cin>>data;
        InsertBST(&T, data);
    }
    printf("中序遍历排序二叉树:");
    InOrder(T);
    cout<<endl;
    while(1){
        cout<<"请输入查找数据(输入-1结束查找): \n";
        cin>>data;
        if(data==-1)
        {
        	break;
		}
		else
		{
			if(SearchBST(T, data))
	            cout<<"找到了\n";
	        else
	            cout<<"找不到\n";			
		}  
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值