代码由四部分组成:
list.c
#include"head.h"
//创建一个二叉树
binary_tree tree_create(void)
{
char x;
binary_tree L;
scanf("%c",&x);
if(x=='#')
{
L=NULL;
}
else
{
L=(binary_tree)malloc(sizeof(Lnode));
if(L==NULL)
{
printf("L is apply failed\n");
exit(1);
}
L->date=x;
//创建左二叉树
L->ltree=tree_create();
//创建右二叉树
L->rtree=tree_create();
}
return L;
}
//遍历根左右
void tree_show(binary_tree L)
{
if(L!=NULL)
{
printf("%c ",L->date);
tree_show(L->ltree);
tree_show(L->rtree);
}
}
//遍历左根右
void tree_show1(binary_tree L)
{
if(L!=NULL)
{
tree_show1(L->ltree);
printf("%c ",L->date);
tree_show1(L->rtree);
}
}
//遍历左右根
void tree_show2(binary_tree L)
{
if(L!=NULL)
{
tree_show2(L->ltree);
tree_show2(L->rtree);
printf("%c ",L->date);
}
}
head.h
#ifndef __HEAD_H
#define __HEAD_H
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char datetype;
typedef struct tree{
datetype date;
struct tree *rchild;
struct tree *lchild;
}Lnode,*stree;
stree tree_create();
void tree_show1(stree L);
void tree_show2(stree L);
void tree_show3(stree L);
#endif
test.c
#include"head.h"
int main(int argc,char *argv[])
{
stree L;
L=tree_create();
if(L==NULL)
{
printf("L create is fail\n");
exit(1);
}
tree_show1(L);
return 0;
}
Makefile
CC=gcc
CFLAGS=-c -Wall -O
objs=list.o test.o
yuxiang:$(objs)
$(CC) -o $@ $^
%*.o:%*.c
$(CC) $(CFLAGS) -c -o $@ $<
.PHONY:clean
clean:
rm -rf *.o yuxiang
输入数据的时候的结点没有左子树或者右子树使用的#表示