#include<iostream>
#include<ctime>
using namespace std;
typedef long ElemType;
typedef class BinarySearchTree_Node
{
public:
ElemTypedata;
BinarySearchTree_Node *left, *right;
}BinarySearchTree_T, *BinarySearchTree_P;
BinarySearchTree_PSearch_BinarySearchTree(BinarySearchTree_P root, ElemType key)//非递归查找
{
BinarySearchTree_P p = root;
while (p)
{
if (p->data == key) return p;
p = (key < p->data) ?p->left : p->right;
}
return NULL;
}
BinarySearchTree_PSearch_BinarySearchTree1(BinarySearchTree_P root, ElemType key)//递归查找
{
if (root == NULL)
return NULL;
if (key > root->data) //查找右子树
return Search_BinarySearchTree(root->right, key);
else if (key < root->data) //查找左子树
return Search_BinarySearchTree(root->left, key);
else
return root;
}
voidInsert_BinarySearchTree(BinarySearchTree_P *root, ElemType data)
{
//初始化插入节点
BinarySearchTree_P p= (BinarySearchTree_P)malloc(sizeof(structBinarySearchTree_Node));
if (!p)
return;
p->data = data;
p->left = p->right = NULL;
//空树时,直接作为根节点
if (*root == NULL)
{
*root = p;
return;
}
//是否存在,已存在则返回,不插入
if (Search_BinarySearchTree(*root, data) != NULL)
return;
//进行插入,首先找到要插入的位置的父节点
BinarySearchTree_P tnode = NULL, troot = *root;
while (troot)
{
tnode = troot;
troot = (data < troot->data) ? troot->left : troot->right;
}
if (data < tnode->data)
tnode->left = p;
else
tnode->right = p;
}
voidCreateBinarySearchTree(BinarySearchTree_P *T, ElemType ElemTypeger)
{
Insert_BinarySearchTree(T, ElemTypeger);
}
void MidOrderTraverse(BinarySearchTree_P T)
{
if (T)
{
MidOrderTraverse(T->left);
cout << T->data << " ";
MidOrderTraverse(T->right);
}
}
int main()
{
long i,t1,t2,t3,t4;
BinarySearchTree_P root = NULL;
cout<<"Create BinarySearchTree ing"<<endl;
for(i=0;i<1000000;i++){
//创建二叉排序树
CreateBinarySearchTree(&root, rand());
}
//MidOrderTraverse(root);
cout <<"complete"<< endl;
ElemType n;
cin>>n;
BinarySearchTree_P result=0;
t1=clock();
for(i=0;i<32767;i++)
result = Search_BinarySearchTree(root, n);
t2=clock();
if (result){
cout<<"\n非递归Search Data:"<<n;
cout << "查找结果:\n" <<"指针:" << result << endl <<"指针的值:"
<< result->data<<" time:"<<((double)t2-t1/1000000.0)<<"ms"<< endl;
}
else cout<<"error"<<endl;
t3=clock();
for(i=0;i<1000000;i++)
result = Search_BinarySearchTree1(root, n);
t4=clock();
if (result){
cout<<("\n递归Search Data: ");
cout << "查找结果:\n" <<"指针:" << result << endl <<"指针的值:"
<< result->data<<" time:"<<((double)t4-t3/1000000.0)<<"ms"<< endl;
}
else cout<<"error"<<endl;
return 0;
}