#include<stdio.h>
#include<stdlib.h>
typedef struct tree
{
int data;
struct tree* lchild;
struct tree* rchild;
}TREE,*ptree;
ptree creatTreenode()
{
ptree p=(ptree)malloc(sizeof(TREE));
if(p==NULL)
{
printf("空间申请失败\n");
return NULL;
}
printf("请输入数据:\n");
scanf("%d",&p->data);
p->lchild=NULL;
p->rchild=NULL;
return p;
}
ptree insertTreenode(ptree root,ptree p)
{
if(root==NULL)
{
root=p;
return root;
}
if(p->data < root->data)
{
if(root->lchild==NULL)
root->lchild=p;
else
root->lchild=insertTreenode(root->lchild,p);
}
else
{
if(root->rchild==NULL)
root->rchild=p;
else
root->rchild=insertTreenode(root->rchild,p);
}
return root;
}
ptree searchTreenode(ptree root,int data)
{
if(root==NULL)
return NULL;
if(root->data==data)
return root;
else if(root->data >= data)
searchTreenode(root->lchild,data);
else if(root->data <= data)
searchTreenode(root->rchild,data);
else
return NULL;
}
void showTreenode(ptree root)
{
if(root==NULL)
return ;
if(root!=NULL)
{
showTreenode(root->lchild);
printf("%d ",root->data);
showTreenode(root->rchild);
}
}
void freeTreenode(ptree root)
{
if(root==NULL)
return ;
if(root->lchild==NULL&&root->rchild==NULL)
{
free(root);
return;
}
else
{
if(root->lchild!=NULL)
freeTreenode(root->lchild);
if(root->rchild!=NULL)
freeTreenode(root->rchild);
}
}
int main()
{
int data;
ptree p,root=NULL;
for(;;)
{
p=creatTreenode();
if(p==NULL)
exit(0);
if(p->data==-1)
{
free(p);
break;
}
root=insertTreenode(root,p);
}
showTreenode(root);
printf("\n");
printf("请输入查找的数据\n");
scanf("%d",&data);
p=searchTreenode(root,data);
if(p!=NULL)
printf("查找的数据data=%d\n",p->data);
else
printf("未找到查找的数据\n");
freeTreenode(root);
printf("\n");
}