#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 = (BTnode*)malloc(sizeof(BTnode));
root->data = x;
root->left = root->right = NULL;
}else{
if(root->data>x){
root->right = CreateTree(root->right, x);
}else{
root->left = CreateTree(root->left, x);
}
}
return root;
}
//前序遍历
void Forder(BTnode*root){
if(root){
printf("%3d ",root->data);
Forder(root->left);
Forder(root->right);
}
}
//中序遍历
void Inorder(BTnode*root){
if(root){
Inorder(root->left);
printf("%3d ",root->data);
Inorder(root->right);
}
}
//后续遍历
void Porder(BTnode*root){
if(root){
Porder(root->left);
Porder(root->right);
printf("%3d ",root->data);
}
}
//主函数
int main (void){
BTnode* root = NULL;
int x; //当前值
int n; //数据的个数
int i; //循环变量
printf("请输入n=");
scanf("%d",&n);
printf("请输入二叉树的结点data\n");
for(i=0;i<n;i++)
{
scanf("%d",&x);
root = CreateTree(root,x);
}
printf("\n前序遍历为:");
Forder(root);
printf("\n中序遍历为:");
Inorder(root);
printf("\n后序遍历为:");
Porder(root);
printf("\n");
}