c语言 创建并用三种方法遍历二叉树
#include <stdio.h>
#include <stdlib.h>
typedef struct bitree{
char data;
bitree *lc,*rc;
}bt;
bt *ct(){
char d;
printf("请输入结点数据,输入#则结束此结点的创建\n");
scanf("%c",&d);
getchar();
if(d=='#'){
return NULL;
}
else{
bt *t=(bt*)malloc(sizeof(bt));
t->data=d;
printf("开始创建%c结点的左孩子结点\n",t->data);
t->lc=ct();
printf("开始创建%c结点的右孩子结点\n",t->data);
t->rc=ct();
return t;
}
}
void preo(bt *t){
if(t!=NULL){
printf("%c",t->data);
preo(t->lc);
preo(t->rc);
}
}
void ino(bt *t){
if(t!=NULL){
ino(t->lc);
printf("%c",t->data);
ino(t->rc);
}
}
void posto(bt *t){
if(t!=NULL){
posto(t->lc);
posto(t->rc);
printf("%c",t->data);
}
}
int main(){
bt *t=ct();
if(t==NULL){
printf("所得二叉树为空");
return 0;
}
printf("\n二叉树创建完毕\n");
printf("先序遍历结果如下:\n");
preo(t);
printf("中序遍历结果如下:\n");
ino(t);
printf("后序遍历结果如下:\n");
posto(t);
return 0;
}