C++ 二叉搜索树实现
#include<cstdio>
#include<iostream>
using namespace std;
typedef struct Node
{
int key;
Node *left;
Node *right;
}Node;
Node *t = new Node;
void Front(Node *p) //前序遍历
{
printf("%d ",p->key);
if(p->left) Front(p->left);
if(p->right) Front(p->right);
}
void Mid(Node *p) //中序遍历
{
if(p->left) Mid(p->left);
printf("%d ",p->key);
if(p->right) Mid(p->right);
}
void Back(Node *p) //后序遍历
{
if(p->left) Back(p->left);
if(p->right) Back(p->right);
printf("%d ",p->key);
}
//插入数据
Node* insert(Node *root,int key)
{
if(!root)
{
Node *p = new Node;
p->key = key;
p->left = p->right = NULL;
return p;
}
else
if(root->key > key) root->left = insert(root->left,key);
else root->right = insert(root->right,key);
return root;
}
//查找数据
bool search(Node *p,int x)
{
if(!p) return false;
else if(x == p->key) return true;
else if(p->key > x) return search(p->left,x);
else return search(p->right,x);
}
int main()
{
int n,x;
while(scanf("%d",&n)!=EOF)
{
t = NULL;
for(int i = 0; i < n; i++)
{
scanf("%d",&x);
t = insert(t,x);
}
Front(t);
printf("\n");
Mid(t);
printf("\n");
Back(t);
printf("\n");
cout<<search(t,115)<<endl;
}
return 0;
}