适用二叉链表存储二叉树,实现二叉树的输入,先序遍历,中序遍历,后序遍历的递归算法,编制main程序调用这些子程序,并输出各遍历结果。
#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct Node
{
struct Node *lchild;
ElemType data;
struct Node *rchild;
/* data */
}Tree;
Tree * create_tree(Tree *t){
//先序创建
ElemType ch;
scanf("%d",&ch);
if(ch == 0)
//t = (Tree *)malloc(sizeof(Tree))
t = NULL;
else{
t = (Tree *)malloc(sizeof(Tree));
t->data = ch;
t->lchild = create_tree(t->lchild);
t->rchild = create_tree(t->rchild);
}
return t;
}
void prior_show(Tree *t){
if(t == NULL){
//printf("THE TREE IS EMPTY\n");
return ;
}else{
printf("%2d",t->data);
prior_show(t->lchild);
prior_show(t->rchild);
}
}
void inorder_show(Tree *t){
if(t == NULL){
//printf("THE TREE IS EMPTY\n");
return ;
}else{
inorder_show(t->lchild);
printf("%2d",t->data);
inorder_show(t->rchild);
}
}
void last_show(Tree *t){
if(t == NULL){
//printf("THE TREE IS EMPTY\n");
return ;
}else{
last_show(t->lchild);
last_show(t->rchild);
printf("%2d",t->data);
}
}
void show(Tree *t, void (* order)(Tree *)){
order(t);
printf("\n");
}
int main(){
Tree *t;
t = create_tree(t);
printf("先序:");
show(t,prior_show);
printf("中序:");
show(t,inorder_show);
printf("后序:");
show(t,last_show);
return 0;
}