#include<stdio.h>
#include<stdlib.h>
//声明
typedef struct node
{
int data;
struct node*left;
struct node*right;
}BTnode;
//先生成一颗二叉排序树
BTnode* CreateTree(BTnode* root,int x)
{
if(!root) //如果root结点为空,创建叶子结点
{
root=(BTnode*)malloc(sizeof(BTnode));
root->data = x;
root->left=root->right=NULL;
}else
{
if(root->data>x)
root->left = CreateTree(root->left,x); //递归调用左
else if(root->data<x)
root->right = CreateTree(root->right,x);//递归调用右
}
return root;
}
//中序遍历
void Inorder(BTnode* root)
{
if(root){
Inorder(root->left);
printf("%3d",root->data);
Inorder(root->right);
}
}
//查找输出数据
BTnode* query(BTnode* root, int key){
if(root&&root->data==key){
return root;
}else if(key <root->data ){
return query(root->left,key);
}else{
return query(root->right,key);
}
}
//主函数
int main (void){
BTnode * root = NULL;
int x; //当前数据
int n; //数据个数
int i; //循环变量
int key; //输入的待查询的数据
printf("请输入n=");
scanf("%d",&n);
printf("请输入二叉树的结点data:\n");
//循环数据生成一颗二叉排序树
for(i=0;i<n;i++)
{
scanf("%d",&x);
root = CreateTree(root,x);
}
//中序遍历
printf("中序遍历为:");
Inorder(root);
printf("\n");
printf("请输入要查询的数据:\n");
scanf("%d",&key);
root = query(root,key);
if(root){
printf("所查询的值%d",root->data);
}else{
printf("没有此值");
}
}