#include<stdio.h>
#include<stdlib.h>
struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
SearchTree Insert(int x, SearchTree T);
struct TreeNode //结点声明
{
int data;
SearchTree left;
SearchTree right;
};
SearchTree Insert(int x, SearchTree T) //建立二叉树(插入结点的方法建立二叉树,小数在左,大数在右)
{
if(T==NULL){
T=malloc(sizeof(struct TreeNode));
T->data = x;
T->left = T->right =NULL;
}
else if(x < T->data)
T->left = Insert(x,T->left);
else if(x > T->data)
T->right = Insert(x,T->right);
return T;
}
void Zhongxu(SearchTree T) //中序遍历(因为特殊的创建方法,导致中序遍历输出为递增的数字)
{
if(T != NULL) {
Find(T->left);
printf("%5d",T->data);
Find(T->right);
}
}
void Xianxu(SearchTree T) //先序遍历
{
if(T != NULL){
printf("%5d",T->data);
Xianxu(T->left);
Xianxu(T->right);
}
}
void Houxu(SearchTree T) //后序遍历
{
if(T != NULL){
Houxu(T->left);
Houxu(T->right);
printf("%5d",T->data);
}
}
int main()
{
SearchTree T=NULL;
int x;
printf("请输入根结点: ");
scanf("%d", &x);
while(x != -1) {
T = Insert(x,T);
printf("请输入值: ");
scanf("%d", &x);
}
printf("先序: ");
Xianxu(T);
printf("\n");
printf("中序: ");
Zhongxu(T);
printf("\n");
printf("后序: ");
Houxu(T);
printf("\n");
}