//实现二叉查找树进行数据查找
#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;
}