main.c
#include "tree.h"
int main()
{
treeptr T=create();//创建二叉树
first_show(T);//先序遍历
printf("\n");
mid_show(T);//中序遍历
printf("\n");
last_show(T);//后序遍历
printf("\n");
freeTree(T);//销毁二叉树
}
tree.h
#ifndef __TREE_H__
#define __TREE_H__
#include <stdio.h>
#include <stdlib.h>
typedef char datatype;
typedef struct node
{
datatype data;
struct node *L;
struct node *R;
}tree,*treeptr;
//创建二叉树
treeptr create();
//先序遍历
void first_show(treeptr T);
//中序遍历
void mid_show(treeptr T);
//后序遍历
void last_show(treeptr T);
//销毁二叉树
void freeTree(treeptr T);
#endif
tree.c
#include "tree.h"
//创建二叉树
treeptr create()
{
datatype e;
scanf("%c",&e);
if(e=='#')
return NULL;
treeptr T=(treeptr)malloc(sizeof(tree));
if(T==NULL)
return NULL;
T->data=e;
T->L=create();
T->R=create();
return T;
}
//先序遍历
void first_show(treeptr T)
{
if(T==NULL)
return;
printf("%c ",T->data);
first_show(T->L);
first_show(T->R);
}
//中序遍历
void mid_show(treeptr T)
{
if(T==NULL)
return;
mid_show(T->L);
printf("%c ",T->data);
mid_show(T->R);
}
//后序遍历
void last_show(treeptr T)
{
if(T==NULL)
return;
last_show(T->L);
last_show(T->R);
printf("%c ",T->data);
}
//销毁二叉树
void freeTree(treeptr T)
{
if (T == NULL)
return;
//销毁左子树
freeTree(T->L);
//销毁右子树
freeTree(T->R);
free(T);
}