代码:
#include <stdlib.h>
#include <stdio.h>
typedef struct Node
{
char data;
struct Node *lchild;
struct Node *rchild;
}*Tree;
//申请空间
Tree create_space()
{
Tree t = (Tree)malloc(sizeof(struct Node));
if(NULL == t)
{
return NULL;
}
t->data = 0;
t->lchild = t->rchild = NULL;
return t;
}
//创建二叉树
Tree create_tree()
{
printf("please write character:\n");
char ch;
scanf(" %c", &ch);
if('#' == ch)
return NULL;
Tree t = create_space();
t->data = ch;
t->lchild = create_tree();
t->rchild = create_tree();
return t;
}
//销毁
void destroy_tree(Tree t)
{
if(NULL == t)
return;
destroy_tree(t->lchild);
destroy_tree(t->rchild);
free(t);
t = NULL;
}
//先序遍历
void first_output(Tree t)
{
if(NULL == t)
return;
printf("%c", t->data);
first_output(t->lchild);
first_output(t->rchild);
}
//中序遍历
void mid_output(Tree t)
{
if(NULL == t)
return;
first_output(t->lchild);
printf("%c", t->data);
first_output(t->rchild);
}
//后序遍历
void last_output(Tree t)
{
if(NULL == t)
return;
first_output(t->lchild);
first_output(t->rchild);
printf("%c", t->data);
}
int main(int argc, const char *argv[])
{
Tree t = create_tree();
printf("先序遍历:\t");
first_output(t);
puts("");
printf("后序遍历:\t");
mid_output(t);
puts("");
printf("中序遍历:\t");
last_output(t);
puts("");
destroy_tree(t);
return 0;
}
效果图: