测试序列:AB#CD###E#FGH##K###
一.头文件btree.h实现
#ifndef __BTREE_H__
#define __BTREE_H__
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef char datatype_bt;
typedef struct btreenode
{
datatype_bt data;
struct btreenode *lchild,*rchild;
}btree_node,*btree_pnode;
extern void create_btree(btree_pnode *T);
extern void pre_order(btree_pnode t);
extern void mid_order(btree_pnode t);
extern void last_order(btree_pnode t);
#endif
二.函数实现btree.c
#include"btree.h"
void create_btree(btree_pnode *T)
{
datatype_bt ch;
scanf("%c",&ch);
if('#' == ch)
*T = NULL;
else
{
*T = (btree_pnode)malloc(sizeof(btree_node));
if(NULL == *T)
{
perror("malloc");
exit(1);
}
(*T)->data = ch;
create_btree(&(*T)->lchild);
create_btree(&(*T)->rchild);
}
}
//先序遍历
void pre_order(btree_pnode t)
{
if(t != NULL)
{
//访问根结点
printf("%c",t->data);
//先序遍历左子树
pre_order(t->lchild);
//先序遍历右子树
pre_order(t->rchild);
}
}
//中序遍历
void mid_order(btree_pnode t)
{
if(t != NULL)
{
//先序遍历左子树
mid_order(t->lchild);
printf("%c",t->data);
//先序遍历右子树
mid_order(t->rchild);
}
}
//后序遍历
void last_order(btree_pnode t)
{
if(t != NULL)
{
//先序遍历左子树
last_order(t->lchild);
printf("%c",t->data);
//先序遍历右子树
last_order(t->rchild);
}
}
三.包含主函数的test.c文件
#include"btree.h"
int main()
{
btree_pnode t;
create_btree(&t);
printf("先序遍历序列\n");
pre_order(t);
puts("");
printf("中序遍历序列\n");
mid_order(t);
puts("");
printf("后序遍历序列\n");
last_order(t);
puts("");
return 0;
}
四.makefile文件实现
CC = gcc
CFLAGS = -Wall -g -O0
SRC = btree.c test.c
OBJS = test
$(OBJS):$(SRC)
$(CC) $(CFLAGS) -o $@ $^
clean:
$(RM) $(OBJS) .*.sw?