//head2.h
#include <stdio.h>
#include <iostream>
using namespace std;
template<class type>
class BinarySortTree
{
private:
typedef struct BinaryNode
{
type data;
BinaryNode* left;
BinaryNode* right;
BinaryNode(type dt,BinaryNode* lt,BinaryNode* rt)
{data=dt;left=lt;right=rt;}
}*bt;
BinaryNode* root,*point;
public:
BinarySortTree(){root=NULL;}
void createtree();
bool finddata(type data);
bool _finddata(bt& t,type);
void buildtree(bt& t,type dt);
void traverse(bt& t);
};
//head.h
#include "head2.h"
#include <iostream>
using namespace std;
template<typename type>
void BinarySortTree<type>::createtree()
{
type data;
if(cin>>data && data!=0)
root=new BinaryNode(data,NULL,NULL);
point=root;
while(cin>>data,data!=0)
buildtree(root,data);
point=root;
cout<<"前序遍历二叉排序树,结果为:\n";
traverse(point);
cout<<endl;
}
template<typename type>
void BinarySortTree<type>::buildtree(bt& t,type dt)
{
if(t==NULL)
t=new BinaryNode(dt,NULL,NULL);
else
{
if(dt<t->data)
buildtree(t->left,dt);
if(dt>t->data)
buildtree(t->right,dt);
}
}
template<typename type>
void BinarySortTree<type>::traverse(bt& t)
{
if(t)
{
cout<<t->data<<" ";
traverse(t->left);
traverse(t->right);
}
}
template<typename type>
bool BinarySortTree<type>::finddata(type data)
{
if(_finddata(point,data))
{
point=root;
return 1;
}
else
{
point=root;
return false;
}
}
template<typename type>
bool BinarySortTree<type>::_finddata(bt& t,type data)
{
if(t)
{
if(t->data==data)
return 1;
if(t->data>data)
return _finddata(t->left,data);
if(t->data<data)
return _finddata(t->right,data);
}
return 0;
}
//main.cpp
// 二叉排序树.cpp : 定义控制台应用程序的入口点。
//#include "stdafx.h"
#include "head.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main()
{
char c=0;
printf("%-20c数据结构与算法分析实验7:二叉排序树\n",c);
BinarySortTree<int> BST;
cout<<"\n建立二叉排序树,请输入结点数据(0表示输入结束):\n";
BST.createtree();
cout<<"查找二叉排序树,请输入要查找的结点:";
int data;
cin>>data;
if(BST.finddata(data))
cout<<"结点找到!\n";
else
cout<<"不存在该结点!\n";
system("pause");
}